0.自定义指令使用方法
<template>
<div>
<input v-color="'green'">
<span v-fontweight="600">私有指令</span>
</div>
</template>
1.自定义全局指令
Vue.directive('color', {
bind: function (el, binding) { // 每当指令绑定到元素上的时候,会立即执行这个 bind 函数,【只执行一次】(dom元素还没有被创建)
console.log(binding.name); //打印结果:color
console.log(binding.value); //打印结果:green
console.log(binding.expression); //'green'
el.style.color = binding.value
},
inserted: function (el) { // inserted 表示元素 插入到DOM中的时候,会执行 inserted 函数【触发1次】
el.focus()
},
updated: function (el) { // 当VNode更新的时候,会执行 updated, 【可能会触发多次】
}
})
//自定义全局指令(简写形式)
Vue.directive('color', function (el, binding) { //注意,这个function等同于把代码写到了 bind 和 update 中去
el.style.color = binding.value
})
2.自定义私有指令
export default {
//自定义私有指令
directives: {
'fontweight': {
bind: function (el, binding) {
el.style.fontWeight = binding.value;
}
}
},
//自定义私有指令(简写形式)
directives: {
'fontweight': function (el, binding) { //注意,这个function等同于把代码写到了 bind 和 update 中去
el.style.fontWeight = binding.value;
}
}
}