Vue provides instructions such as V-model V-HTML, but sometimes we need to customize the instructions to meet our needs.
Custom directives are provided
Bind: called once, when the directive is first bound to an element. You can use this hook function to define an initialization action that will be performed once at bind time.
Inserted: Called when the bound element is inserted into its parent (the parent is called if it exists, not in the document).
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 (see below for detailed hook function parameters).
ComponentUpdated: Called when the template to which the bound element belongs completes an update cycle.
Unbind: Called only once, when an instruction is unbound from an element.
Example 1: Refresh page input automatically get focus:
<div id="app">
<input type="text" v-focus/>
</div>
Copy the code
// Register a global custom directive v-focus
Vue.directive('focus', {
// When the binding element is inserted into the DOM.
inserted: function (el,binding) {
// Focus elementsel.focus(); }});newVue({el:'#app'
});
Copy the code
Example 2: A drag and drop demo:
1) The dragged element must be positioned with position before it can be dragged;
2) After the completion of the custom instruction, Vue needs to be instantiated to mount elements;
Inserted: Called when the bound element is inserted into the parent.
<style type="text/css">
.one,.two{
height:100px;
width:100px;
border:1px solid #000;
position: absolute;
-webkit-user-select: none;
-ms-user-select: none;
-moz-user-select: -moz-none;
cursor: pointer;
}
.two{
left:200px;
}
</style>
<div id="app">
<div class="one" v-drag>Drag and drop one,</div>
<div class="two" v-drag>Drag and drop two</div>
</div>
Copy the code
Vue.directive('drag', {
inserted:function(el){el. &western nm &western informs the &western wn =function(e){
let l=e.clientX-el.offsetLeft;
let t=e.clientY-el.offsetTop;
document. &western nm &western usem &western ve =function(e){
el.style.left=e.clientX-l+'px';
el.style.top=e.clientY-t+'px'; }; El. &western nm &western useup =function(){
document. &western nm &western usem &western ve =null; El. &western nm &western useup =null; }}}})newVue({el:'#app'
});
Copy the code