In addition to the built-in instructions (v-show,v-model), vue allows us to customize the instructions
To create a custom instruction, register the instruction (take the input box to get the focus as an example)
1, Register global directives:
// Register a global custom instruction ` v-focus` Vue.directive('focus', { // When the bound element is inserted into the DOM inserted: function (el,binding) { // dom elements bound by the current instruction //console.log(el); // Parameter, modifier, value v-instruction Name: parameter. Modifier = value // console.log(binding) // Focusing element el.focus() } })
2, Register local instruction:
directives: { focus: { // Definition of instructions inserted: function (el) { el.focus() } } }
It is also easy to use: you can use v-focus directly on the element:
<input type="text" v-focus/>
Here's another example of a custom command: drag and drop
Vue.directive('drag', { // Execute when an instruction is bound to an element bind(el, binding) { // console.log('bind'); // dom elements bound by the current instruction //console.log(el); // Parameter, modifier, value v-instruction Name: parameter. Modifier = value // console.log(binding) el.onmousedown = function(e) { var e = e||event; let disX = e.clientX - el.offsetLeft; let disY = e.clientY - el.offsetTop; document.onmousemove = function(e) { var e = e||event; let L = e.clientX - disX; let T = e.clientY - disY; if (binding.modifiers.limit) { if (L < 0) { L = 0; } } el.style.left = L + 'px'; el.style.top = T + 'px'; }; document.onmouseup = function() { document.onmousemove = null; }; return false; } } });
It's easy to use, just add v-drag or v-drag.limit to the element
<div id="div1" v-drag.limit></div> <div id="div2" v-drag></div>