Vue: Custom Directives

Haixiang Yan
2 min readJan 12, 2019

--

Directives is like a helper for component. There are some useful directives that provided by Vue, such as v-model, v-for, v-if and etc, but sometimes we may need to define our directives to help to add some behaviors for our components.

Register

The way to register a directive is similar to register a component. We can register globally or locally. The different thing is changing ‘components’ to ‘directives’.

Globally Registration

Vue.directive('focus', {
inserted: function (el) {
console.log('Hello, I am ' + el)
}
})

Locally Registration

directives: {
focus: {
inserted: function (el) {
console.log('Hello, I am ' + el)
}
}
}

Hook Functions

Remember what we say: Directive is a helper for component to add some behaviors, so it is used to interact with binding component during its lifecycle. That’s why directive has hook functions.

  1. bind(): Called only once, when the directive is first bound to the element.
  2. insert(): Called when the bound element has been inserted into its parent node.
  3. update(): Called after the containing component’s VNode has updated.
  4. componentUpdated(): Called after containing component’s VNode and the VNodes of its children has updated.
  5. unbind(): Called only once, when the directive is unbound from the element.

Generally, we use bind() , insert() and unbind() .

Hook Arguments

There are 4 arguments that will be passed to the hook functions: el, binding, vnode and oldNode . Most of time, we use el and binding .

  • el: The element the directive is bound to.
  • binding: An object containing the following properties.
{
name: 'Name of directive',
value: 'Value passed to the directive',
oldValue: 'Previous value',
expression: 'Expression of the binding as a string',
arg: 'Argument passed to the directive',
modifiers: 'Object containing modifiers'
}
  • vnode: Virtual DOM

Example

You may confuse about the meanings of these arguments. Let’s define a directive like this:

What is does is to print out the properties when binding the <pre/> element. Then we use it to <pre/> .

The result will be:

Result of Rending

In summary, the properties of this directive is like this:

Summary

--

--