Vue allows you to register custom directives, which are used for low-level operations on ordinary DOM elements.

The first input automatically gets focus

1. Register a global directive

<input type="text" V-model ="num" v-focus> vue. directive('focus', {// When the bound element is inserted into the DOM: Function (el) {// Focus element el.focus(); }})Copy the code

2. Register a local component

< INPUT type="text" V-model ="num" V-focus > directives: {focus: Inserted: function (el) {console.log(el, 'inserted') // Sets the focus el.focus(); }}},Copy the code

Hook function

// HTML page <input type="text" v-model="num" V-focus :foo.x="message" v-if="num<20"> 'hello! ',} // Register local component directives: {focus: {// Only once, when the directive is first bound to an element, where one-time initialization is possible. function (el, vnode) { console.log(el, 'bind'); }, // Inserted: function (el) {console.log(el, 'inserted') // Set the focus el.focus(); }, // All components are called when their vNodes are updated, but this may happen before their child vNodes are updated. Directive values may or may not have changed, but you can ignore unnecessary template updates by comparing the values before and after the update: function (el, binding, vnode, oldVnode) { console.log('update start'); console.log(binding, 'binding', new Date().toLocaleString()); // <input type="text" v-model="num" v-focus:foo.x="message" v-if="num<20"> // data: { // num: 1, // message: 'hello! '//}, //binding: an object containing the following property // name: the directive name does not include the v prefix focus // value: the directive binding value hello! // oldValue: The preceding value of an instruction binding, available only in the UPDATE and componentUpdate hooks, regardless of whether the value changes // expression Specifies an instruction expression in the form of a string, such as v-focus:foo.x="message", where the expression is Message // arg: the argument passed to the instruction, optional, for example, in v-focus:foo.x="message", the argument is foo // X ="message", where the modifier object is {x:true}}, // calls componentUpdated when all vNodes and their children are updated: function (el) { console.log('update end'); console.log(el, 'componentUpdated'); Unbind: function (el) {console.log(el, 'unbind'); unbind: function (el) {console.log(el, 'unbind'); }}},Copy the code

Dynamic instruction parameter

// HTML <div V-fixed :[position]="px" class="odiv"></div> // vue data: {position: 'right', px: 300}, // vue custom function part // dynamic command parameter setting fixed positioning distance right 300px fixed: {bind: function (el, binding, vnode) { el.style.position = 'fixed' el.style[binding.arg] = binding.value + 'px' } }Copy the code