How to customize instructions in vue2

effect:

When it is necessary to perform low-level operations on ordinary DOM elements, custom instructions are used. In addition to providing default built-in instructions, Vue also allows developers to customize instructions according to actual conditions. Global custom directives can be registered, and local directives can also be registered.

parameter:

The first parameter is the custom command name (the command name does not need to be prefixed with v-, the default is automatically prefixed, and the prefix must be added when using the command), the second parameter can be object data, or it can be a directive function.

 <div id="app" class="demo">
     <!-- 全局注册 -->
     <input type="text" placeholder="我是全局自定义指令" v-focus>
 </div>
 <script>
 // 注册一个全局自定义指令 `v-focus`
 Vue.directive('focus', {
   // 当被绑定的元素插入到 DOM 中时……
   inserted: function (el) {
     // 聚焦元素
     el.focus()
   }
 })
 ​
 ​
 //注册局部指令
 directives: {
   focus: {
     // 指令的定义
     inserted: function (el) {
       el.focus()
     }
   }
 }
 ​
 </script>

Hook functions for custom directives

An instruction definition object can provide the following hook functions (all optional):

  • bind : Called only once, when the directive is bound to the element for the first time. One-time initialization settings can be performed here
  • inserted : Called when the bound element is inserted into the parent node (only the parent node is guaranteed to exist, but not necessarily inserted into the document).
  • update : Called when the component's VNode is updated, but it may happen before its child VNode is updated. The value of the directive may or may not have changed. But you can ignore unnecessary template updates by comparing the values ​​before and after the update.
  • componentUpdated : Called after the VNode of the component where the command is located and its child VNodes are all updated.
  • unbind : Called only once, when the directive is unbound from the element.

This paragraph is copied from the official document, I believe it should be understood at a glance.

So how to use these hook functions? Let's take a look at the parameters of the hook function first. The command hook function will be passed the following parameters:

  • el : The element bound to the instruction can be used to directly manipulate the DOM, which is the element where the instruction is placed.
  • binding : An object, which contains several attributes. There are not many explanations here, and there are very detailed descriptions in the official documents.
  • vnode : The virtual node generated by Vue compilation.
  • oldVnode : the previous virtual node, only available in update and componentUpdated hooks.

Guess you like

Origin blog.csdn.net/qq_52006046/article/details/128768450