How to create custom directives in Vue.js
Overview
We use directives to instruct Vue.js to do something, that is, to exhibit a specific behavior in the DOM. For example, v-if, v-for, v-on, etc., are some of the built-in directives which tell Vue.js to do something for us. We add these directives to the HTML element as their attributes.
What if we want to use a directive that Vue.js does not provide? In that case, Vue.js allows us to create our own custom directive.
Before creating a custom directive, let's see the syntax of registering and using a custom directive.
Syntax
A custom directive can be registered in the following ways.
1. Globally
Vue.directive('directive-name', {bind: function (el, binding, vnode) {// code}});
2. Locally
directives: {directive-name: {bind: function (el, binding, vnode) {// code}}}
Let's break down the above snippet.
- We use the
Vue.directiveto register a custom directive globally. It is included in themain.jsfile. - We use the
directivesobject to register a custom directive locally. It is included in the component's script. - Next, we use the
bind()function to bind the specified values to the element. This function accepts the following parameters. el: This element is to be bound with the custom directive.binding: This is an object that contains all the data passed to thebind()function.vnode: This is the underlying V-node that represents the bounded element.
Syntax
We can use a custom directive as follows:
<element directive-name></element>
Example
Let’s see how to create a custom directive. In this example, we'll create a simple directive, color, that will apply specified color on the bounded p element. We will also register this directive locally.
Let's jump to the code.
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
// uncomment the lines 8-14
// to register the directive globally
// Vue.directive("color", {
// bind(el, binding) {
// el.style.color = binding.value;
// }
// });
new Vue({
render: h => h(App),
}).$mount('#app')
Explanation
In the file Example.vue:
- Lines 3–5: We create three
pelements, bind our custom directivecolor, and pass the specified color for eachpelement as an argument. - Lines 10–16: We create a custom directive
colorand register it locally. This directive will bind the HTML element's color with the specified color.
In the file main.js:
- Lines 8–14: We create the same directive
colorand register it globally. It's commented out since the same directive is registered locally as well. If we remove the local directive and uncomment the specified lines inmain.js, then the directive will get registered globally and the output will be the same.
In the output, we can see that each of the p elements has the color that is specified in the v-color directive. Thus, we can confirm that our custom directive is registered correctly and ready to use.