In Vue, when we usually use data-driven views, the internal instructions sometimes cannot solve some needs. At this time, Vue gives us a very useful thing
This word is the keyword for us to write custom instructions. The definition instructions of
provide us with several hook functions. At this time, you You must be curious about what a hook function is. To put it simply, it is a concentrated expression of the status
##bind: Called only once, the instruction is Called once when bound to an element. Use this hook function to define an initialization action that is executed once when binding.
inserted: Called when the bound element is inserted into the parent node (it can be called as long as the parent node exists and does not have to exist in the document).
update: Called when the template where the bound element is located is updated, regardless of whether the binding value changes. By comparing the binding values before and after the update, unnecessary template updates can be ignored (see below for detailed hook function parameters).
componentUpdated: Called when the template where the bound element is located completes an update cycle.
unbind: Called only once, when the instruction is unbound from the element.
Let’s start with the code, so that we can better understand how to do custom instructions
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><script src="https://unpkg.com/vue/dist/vue.js?1.1.11"></script></head><body><div id="app"><div class="ab" v-css="{'color':'red','font-size':'30px'}">hello</div><input type="text" v-focus></div> </body></html>
Vue.directive("css",{//钩子函数 ,el就是当前元素 inserted(el,binding){//el绑定的元素本身//binding就是css指令里面的的对象元素let styleobj=binding.value,arr=[];for(let key in styleobj){ arr.push(key+":"+styleobj[key]) } arr=arr.join(";"); el.style.cssText=arr; }, bind(el,binding) {//指令绑定在元素上时候执行,只执行一次 } });new Vue({ el:'#app', data:{ show:true}, directives:{ focus:{ inserted(el,binding){//el绑定的元素本身//binding就是css指令里面的的对象元素 el.focus(); } } } });
new Vue, This is our global custom directive template method
css is the name of the custom directive{}We can just write the hook function inside itAll our hook functions will basically have two parameters name:{
}
}
The above is the detailed content of Implementation of internal custom instructions and global custom instructions. For more information, please follow other related articles on the PHP Chinese website!