三(5)、指令的作用和自定义指令 ------ 2020-04-
2020-04-19 本文已影响0人
自己写了自己看
1、指令的作用:
指令的作用就是操作DOM 有特定的功能;
2、自定义指令
第一种:
Vue.directive('color', function (el, bindings, vnode){
console.log(el, bindings, vnode);
})
1、el:当前元素;
2、binding:
{
name: "color"
rawName: "v-color"
modifiers: {}
def: {bind: ƒ, update: ƒ}
}
3、vnode:虚拟DOM,这个对象中的context属性是当前指令所在
的上下文;
第二种:
let vm = new Vue({
el: "#app",
data: {},
directives: {
color(el, bindings, vnode) {
console.log(el, bindings, vnode);
},
},
});
// 上面这两种绑定方法,默认调用的是指令中的 bind和update两个
// 指令的钩子函数
3、自定义指令的三个常用的钩子函数
color: {
bind(el) {
// el 绑定到页面上就执行,此时DOM未插入到页面上
},
inserted(el) {
// el插入到页面中时执行,此时DOM已插入到页面上
},
update(el) {
// 当指令依赖的数据或者当前组件依赖的数据发生变化时执行
},
}