“This is the 12th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

1. What is the VUE directive

Directives are small commands that can be written in DOM elements. They are prefixed with v-, which vUE recognizes as an instruction and maintains syntactic consistency. \

V-once, V-show, V-if, V-else, V-else, V-FOR, V-HTML, V-text, V-bind, V-ON, V-model

In + array/object/array of objects/number, index starts from 1 if in is followed by a number, otherwise index starts from 0. (2) As of 2.2.0, v-bind must be used to bind the key attribute, and the key must be unique. ③ The key attribute can only be of the type number or string, not an object.


2. Customize the instruction life cycle

  1. Bind: called once, when the directive is first bound to an element. Use this hook function to define an initialization action that will be performed once on the binding.
  2. Inserted: Called when the bound element is inserted into its parent (the parent is called if it exists, not in the document).
  3. Update: Called when the template to which the element is bound is updated, regardless of whether the binding value changes. Unnecessary template updates can be ignored by comparing the binding values before and after the update.
  4. ComponentUpdated: Called when the template to which the bound element belongs completes an update cycle.
  5. Unbind: Called only once, when an instruction is unbound from an element.
The unbind parameters' el ', 'binding', 'vnode', and 'oldVnode' el ': directives bind elements that can be used to manipulate the DOM directly. 'binding' : an object containing the following property: 'vnode' : a virtual node generated by Vue compilation. 'oldVnode' : last virtual node, available only in the 'Update' and 'componentUpdated' hooks.Copy the code

All parameters except el should be read-only and should not be modified. If you need to share data between hooks, it is recommended to do so through the element’s dataset.


3. Implementation of custom instructions

Directive ('focus', {// When a bound element is inserted into the DOM... Inserted: function (el) {// Focus element el.focus()}})Copy the code

If you want to register local directives, the component also accepts a caching option:

Inserted: function (EL) {el.focus()}}Copy the code

You can then use the new V-focus property on any element in the template, as follows:

<input v-focus>
Copy the code