1.局部指令
new Vue({
directives:{指令名:配置对象}
})
或
new Vue({
directives(指令名:回调函数)
})
2.全局指令:
Vue.directive(指令名, 配置对象)
或
Vue.directive(指令名,回调函数)
配置对象的三个回调:
1.bind:指令与元素成功绑定时
2.inserted:指令所在的元素被插入到页面时
3.update:指令所在的模板被重新解析时
备注:
1.指令定义时不加 v- ,但使用时要加 v-
2.指令名如果是多个单词,要使用 kebab-case命名 不要用camelCase命名(小驼峰命名)
<div id="root">
<h2>当前的n值是:<span v-text="n"></span> </h2>
<h2>放大10倍后的n值是:<span v-big="n"></span> </h2>
<!-- <h2>放大10倍后的n值是:<span v-big-number="n"></span> </h2> -->
<button @click="n++">点我n+1</button>
<hr />
<input type="text" v-fbind:value="n">
</div>
<script>
Vue.config.productionTip = false; //设置为 false 以阻止 vue 在启动时生成生产提示。
/* // 定义全局指令 函数式
Vue.directive('big', function (element, binding) {
element.value = binding.value
})
// 全局指令 对象式
Vue.directive('fbind',{
// 指令与元素成功绑定时(一上来)
bind(element, binding) {
element.value = binding.value
},
// 指令所在的元素被插入到页面时
inserted(element, binding) {
element.focus()
},
// 指令所在的模板被重新解析时
updated(element, binding) {
element.value = binding.value
}
}) */
new Vue({
el: '#root',
data: {
n: 1
},
// 局部指令
directives: {
// big函数何时会被调用?1.指令与元素成功绑定时(一上来) 2.指令所在的模板被重新解析时
big(element, binding) {
element.innerText = binding.value * 10
console.log('big', this); //此处的this是window
},
// 'big-number'(element,binding){
// element.innerText = binding.value *10
// },
// 对象式
fbind: {
// 指令与元素成功绑定时(一上来)
bind(element, binding) {
element.value = binding.value
},
// 指令所在的元素被插入到页面时
inserted(element, binding) {
element.focus()
},
// 指令所在的模板被重新解析时
update(element, binding) {
element.value = binding.value
},
}
}
})
</script>