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.
A custom directive can be registered in the following ways.
Vue.directive('directive-name', {bind: function (el, binding, vnode) {// code}});
directives: {directive-name: {bind: function (el, binding, vnode) {// code}}}
Let's break down the above snippet.
Vue.directive
to register a custom directive globally. It is included in the main.js
file.directives
object to register a custom directive locally. It is included in the component's script.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 the bind()
function.vnode
: This is the underlying V-node that represents the bounded element.We can use a custom directive as follows:
<element directive-name></element>
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')
In the file Example.vue
:
p
elements, bind our custom directive color
, and pass the specified color for each p
element as an argument.color
and register it locally. This directive will bind the HTML element's color with the specified color.In the file main.js
:
color
and 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 in main.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.