My Journey

Writing custom directives in Vue.js

January 28, 2022

If you’ve worked with Vue.js, you most probably have used one of the built-in directives v-if, v-show, v-model,v-on, v-bind, v-html, etc. and know about their functionality.

Today, we are going to write a custom directive v-pin that sets the element at a fixed position from the top.

We can either write a global directive that is available everywhere in our app or a local directive that is only available in the component where its defined.

📦 Local Directive

Components accept a directives option and we can define our v-pin directive as below

<script>
export default {
    directives: {
        pin: {
            bind: function (el, binding, VNode) {
                el.style.position = 'fixed'
                el.style.top = binding.value + 'px'
            }
        }
    }
}
</script>

We have defined our directive locally and now we’ll see how we can register it globally.

🌍 Global Directive

We can register our directive globally in the main.js file of our project as follows

Vue.directive('pin', {
  bind: function (el, binding, VNode) {
        el.style.position = 'fixed'
        el.style.top = binding.value + 'px'
  }
})

and then we can use this directive anywhere in our project like this

and in the template of our component we can bind any element to this directive as below

    <template>
        <div v-pin="100">I'm fixed at 100px from top</div>
    </template>

We used v-pin directive in our component’s template and provided 100 as value to the directive.

In the directive defination we used bind hook which is called when the component is inserted into the DOM. Directive defination has these hooks

🪝 Directive Hooks

1. bind:

Called when the directive is first bound to the element.

2. register:

Called when the bound element is first inserted into the DOM.

3. updated:

Called when component’s Vnode, which contains the directive, is updated but before its children have updated.

4. componentUpdated:

Called when component’s Vnode and it’s children have updated.

5. unbind:

Called when directive is unbound from the element.

🍱 Hook Arguments

Each of these hooks accepts three arguments el, binding, and VNode .

1. el:

The element bounded to the directive.

2. binding:

Anobject which has these properties name, value, oldValue, expression, arg, modifiers, etc.

3. VNode:

Allows you to refer directly to the node in the virtual DOM if you need to.

🎯 Conclusion

This is all one needs to know to write custom directives in Vue.js

Peace ✌️


📝 Thoughts by Zahid Jabbar.
A developer.

👋 Say hi