Syntax in vue.js 2
In Vue 2, custom directives were created by using the hooks listed below to target an element’s lifecycle, all of which are optional:
- bind - Occurs once the directive is bound to the element. Occurs only once.
- inserted - Occurs once the element is inserted into the parent DOM.
- update - This hook is called when the element updates, but children haven't been updated yet.
- componentUpdated - This hook is called once the component and the children have been updated.
- unbind - This hook is called once the directive is removed. Also called only once.
Here’s an example of this:
<p v-highlight="'yellow'">Highlight this text bright yellow</p>
Vue.directive('highlight', {
bind(el, binding, vnode) {
el.style.background = binding.value
}
})
Here, in the initial setup for this element, the directive binds a style by passing in a value, that can be updated to different values through the application.
Syntax in Vue.js 3
In Vue 3, however, we’ve created a more cohesive API for custom directives. As you can see, they differ greatly from our component lifecycle methods even though we’re hooking into similar events. We’ve now unified them like so:
- bind → beforeMount
- inserted → mounted
- beforeUpdate: new! This is called before the element itself is updated, much like the component lifecycle hooks.
- update → removed! There were too many similarities to updated, so this is redundant. Please use updated instead.
- componentUpdated → updated
- beforeUnmount: new! Similar to component lifecycle hooks, this will be called right before an element is unmounted.
- unbind -> unmounted
The final API is as follows:
const MyDirective = {
beforeMount(el, binding, vnode, prevVnode) {},
mounted() {},
beforeUpdate() {}, // new
updated() {},
beforeUnmount() {}, // new
unmounted() {}
}
The resulting API could be used like this, mirroring the example from earlier:
<p v-highlight="'yellow'">Highlight this text bright yellow</p>
const app = Vue.createApp({})
app.directive('highlight', {
beforeMount(el, binding, vnode) {
el.style.background = binding.value
}
})
Now that the custom directive lifecycle hooks mirror those of the components themselves, they become easier to reason about and remember!