- Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Front-end development will inevitably encounter the use of custom instructions, but due to the usual use of some content is always easy to forget, so specially use this article to record the detailed use of custom instructions.
1. Instruction registration
Custom instructions are classified into global registration and local registration
// Global registration
Vue.directive('xxx', {
bind: function() {
// ...}})// Local registration
var app = new Vue({
el: '#app'.directives: {
xxx: {
// ...}}})Copy the code
2. Instruction attributes
- Vue2.0 version
bind
The: directive is called the first time it is bound to an element and is executed only once. This is where you can perform one-time initialization Settings.inserted
: is called when the bound element is inserted into the DOM of the parent node (only if the parent node exists).update
: called when the component is updated.componentUpdated
: called when components and subcomponents are updated.unbind
: is called when an instruction is unbound from an element and is executed only once.
- Vue3.0 version
created
: called before the attribute or event listener of the bound element is applied. The instruction needs to be appended in the normalv-on
This is useful when the event listener is called before the event listener.beforeMount
Called when the directive is first bound to an element and before the parent component is mounted.mounted
: called after the parent component of the bound element has been mounted.beforeUpdate
: called before updating the VNode containing the component.updated
: in a VNode that contains componentsVnodes and their childrenCall after update.beforeUnmount
: called before uninstalling the parent component of the bound elementunmounted
: is called only once when the directive is unbound from an element and the parent component is unmounted.
The 3.0 hook function is different from the 2.0 hook function.