vue3.0 Custom Instructions (Summary of Knowledge Points of drectives

  • 2021-10-15 09:42:11
  • OfStack

In most cases, you can manipulate the data to modify the view, or vice versa. However, it is still inevitable to operate the native DOM occasionally. At this time, you can use custom instructions.

For example, if you want the text box of your page to auto-focus, we might do so without learning the custom instructions.


const app = Vue.createApp({
 mounted(){
  this.$refs.input.focus();
 }, 
 template: `<input type="text" ref="input" />`,
});

In the mounted hook function, get the DOM element that needs to be focused through $refs, and then call focus method to complete the autofocus function.

Basic use

The above approach has already achieved the function we need, but if we have multiple components that need this function, we can only copy this code and re-implement the logic. Let's look at what we should do if we use custom instructions.


const app = Vue.createApp({
 //  Pass  v-[ Custom instruction name ]  Bind custom instructions 
 template: `<input type="text" v-focus/>`,
});
//  Registration 1 Global custom instructions 
app.directive('focus',{
 //  When the bound element is inserted into the DOM Execute when ..
 mounted(el){
  el.focus();
 }
})

As above, we defined a global custom instruction focus and bound it to the input element that needs to be focused through v-focus. If other components or modules also need focus function, simply bind this instruction.

Hook function of custom instruction

When we define the instruction above, we will find that it contains mounted hook function, and the instruction also provides the following hook function, which we list for you in the form of code.


app.directive('directiveName', {
 //  Before mounting the instruction binding element 
 beforeMount(el) {},
 //  After the instruction binding element is mounted, 
 mounted(el, binding) {},
 //  Before the instruction binding element triggers modification due to data modification 
 beforeUpdate(el) {},
 //  After the instruction binding element triggers modification due to data modification, 
 updated(el) {},
 //  Before the instruction binding element is destroyed 
 beforeUnmount(el) {},
 //  After the instruction binding element is destroyed, 
 unmounted(el) {},
});

The effect is not listed in 11. If you are interested, you can try to trigger these hook functions respectively. Instruction hook functions are mostly similar to components, so we can compare them.

Dynamic instruction parameters

Next, let's look at another example.


const app = Vue.createApp({
 template: `<div class="box" v-abs-top="num" style="position:absolute;" ></div>`,
});
//  In many cases, you may want to  mounted  And  updated  Triggers the same behavior, regardless of other hooks, just write 
app.directive('absTop', (el) => {
 el.style[binding.arg] = '100px';
});

We bind the absTop instruction to the div element, the div element itself is positioned as absolute, and the instruction execution makes the top of the bound element 100px. At this point, I want to be able to pass a parameter when binding the instruction, so that the top value of the element can be changed according to the parameter. The code is as follows:


const app = Vue.createApp({
 data() { return { num: 100 } },
 template: `<div class="box" v-abs-top="num"></div>`,
});
app.directive('absTop', (el, binding) => {
 el.style.top = binding.value + 'px';
});

Elements can pass in dynamic parameters via v-directive= "value", and instructions receive parameters via the second parameter of the hook function, binding. value.

If other elements may not modify the value of top, they may be left, right or bottom, can the instruction be specified dynamically? In fact, it can be done. First, we modify the template to:


<div class="box" v-abs:left="num"></div>

Then modify the instruction itself


app.directive('absTop', (el, binding) => {
 el.style[binding.arg] = binding.value + 'px';
});

In v-mydirective: [argument] = "value", arguments can also be dynamically changed, so that the above requirements can be perfectly realized.

Use of components

The binding directive in a component is no different from the DOM element binding directive, which takes the component's primary root DOM to operate on. However, it should be noted that in vue 3.0, components may have multiple root nodes, and it is problematic to bind instructions to multiple root node components.

Local custom instruction

Finally, let's briefly talk about how to define local custom instructions.


const app = Vue.createApp({
directives: {
  focus: {
   //  Definition of instructions 
   mounted(el) {
    el.focus()
   }
  }
 }
}

Local instruction definition and global instruction are basically the same. As shown above, it is enough to define directives in the component.

Summarize

Custom instructions can extract the logic of native DOM operations. Therefore, the application scope of instructions is mainly manifested in that when some operations involve the bottom layer of DOM, and the operation logic may be used in many places, it is suitable to encapsulate these logics with instructions.


Related articles: