1\只是方法名由component 改为了directive 。上例只是注册了自定义指令
v-focus ,还没有实现具体功能,下面具体介绍自定义指令的各个选工页。
自定义指令的选项是由几个钩子函数组成的,每个都是可选的。
• bind : 只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定
时执行一次的初始化动作.
• inserted : 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于document 中) .
• update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后
的绑定值,可以忽略不必要的模板更新。
• componentUpdated : 被绑定元素所在模板完成一次更新周期时调用.
v-focus ,还没有实现具体功能,下面具体介绍自定义指令的各个选工页。
自定义指令的选项是由几个钩子函数组成的,每个都是可选的。
• bind : 只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定
时执行一次的初始化动作.
• inserted : 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于document 中) .
• update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后
的绑定值,可以忽略不必要的模板更新。
• componentUpdated : 被绑定元素所在模板完成一次更新周期时调用.
• unbind : 只调用一次,指令与元素解绑时调用。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script> </head> <body> <div id="app"> <div v-lang="color">{{num}}</div> <div v-lang2="color">test</div> <p><button @click="add">add</button></p> </div> <p> <button onclick='unbind()'>解绑</button> </p> </body> <script type="text/javascript"> function unbind() { vm.$destroy();//另外起一个方法解绑 } Vue.directive('lang', { //五个注册指令的钩子函数 bind: function() { //被绑定 console.log('1 - bind'); }, inserted: function() { //绑定到节点 console.log('2 - inserted'); }, update: function() { //组件更新 console.log('3 - update'); }, componentUpdated: function() { //组件更新完成 console.log('4 - componentUpdated'); }, unbind: function() { //解绑 console.log('5 - bind'); } }); Vue.directive('lang2', { //五个注册指令的钩子函数 bind: function() { //被绑定 console.log('1 - bind2'); }, inserted: function() { //绑定到节点 console.log('2 - inserted2'); }, update: function() { //组件更新 console.log('3 - update2'); }, componentUpdated: function() { //组件更新完成 console.log('4 - componentUpdated2'); }, unbind: function() { //解绑 console.log('5 - bind2'); } }); var vm = new Vue({ el: "#app", data: { num: 10, color: 'red' }, methods: { add: function() { this.num++; } } }); </script> </html>https://www.cnblogs.com/lhl66/p/7492444.html