
Directives
Directives play an important role in a Vue application. They reactively apply changes to the DOM when the value of its expression changes. For example, v-for renders the element or data block multiple times based on the source data, and v-on attaches listeners to a DOM element. Besides using the built-in directives, you can also create custom directives. To do that, you create directive definition objects and register them, either globally using Vue.directive() or locally to a component by using the directives property of that component.
In the definition object of a directive, you can add the following hook functions for Vue.js to notify the directive about what happens outside so that it can apply different logic accordingly:
- bind: Called only once when Vue.js first binds the directive to the element. This is where you perform the one-time setup.
- inserted: Called when Vue.js has inserted the bound element into its parent node. However, the parent node might not have been inserted into the DOM at this moment.
- update: Called when Vue.js has updated the containing component's VNode, but possibly before updating the VNodes of the component's children. We will talk about VNodes later.
- componentUpdated: Called after Vue.js has updated the containing component's VNode and the VNodes of its children.
- unbind: Called only once when Vue.js has unbound the directive from the element.
A good example of custom directives is to create one to automatically focus a forms input after a page has opened. Let's create a global directive, v-focus, and use it on the add message textarea of our Messages App.
Let's have a look at the directives/focus.directive.js file:
// The following example is borrowed from
// https://vuejs.org/v2/guide/custom-directive.html
// Register a global custom directive called `v-focus`
Vue.directive('focus', {
// When the bound element is inserted into the DOM...
inserted: function (el) {
// Focus the element
el.focus();
}
});
Let's have a look at the index.html file:
...
<textarea v-focus ...></textarea>
...
<script type="module">
import MessageList from './components/MessageList.js';
import ‘./directives/focus.directive.js';
...
</script>
We name our directive files in this format: ${directiveName}.directive.js. In this way, when you open it in your editor, you can know it is a directive from the suffix.