自定义指令是用来干什么的呢? 获取标签,扩展额外的功能
有两种注册方法:
① 全局注册
Vue.directive('指令名',{
// 可以对el标签扩展额外功能
inserted (el) {},
// bind函数只调用1次: 当指令第一次绑定到元素时调用,当DOM更新时bind函数不会被触发。
// 如果上面指令赋值,则接收第二个参数,官方指定叫做binding
bind (el,binding) {},
// update函数会在每次DOM更新时被调用。
update(el, binding) {},
// 指令所在组件的 VNode及其子 VNode全部更新后调用。
componentUpdated() {},
// 只调用一次,指令与元素解绑时调用
unbind() {},
})
② 局部注册
directives {
//focus 是指令名
focus: {
// 可以对el标签扩展额外功能
inserted (el) {},
// bind函数只调用1次: 当指令第一次绑定到元素时调用,当DOM更新时bind函数不会被触发。
// 如果上面指令赋值,则接收第二个参数,官方指定叫做binding
bind (el,binding) {},
// update函数会在每次DOM更新时被调用。
update(el, binding) {},
// 指令所在组件的 VNode及其子 VNode全部更新后调用。
componentUpdated() {},
// 只调用一次,指令与元素解绑时调用
unbind() {},
}
}
tip:全局注册是directive节点, 局部注册是 directives节点
我们来稍微用一下全局指令:
全局指令在main.js中
/*
全局自定义指令
*/
Vue.directive('focus', {
inserted(el) {
el.focus()
}
})
自己需要用的vue文件
<div>
<h2>自定义指令</h2>
<input type="text" v-focus />
</div>
我们再来用一下局部指令:
在自己需要的vue文件中:
<div>
<h2>局部指令</h2>
<p v-colors>局部指令</p>
</div>
directives: {
colors: {
inserted (el) {
el.style.color = 'red'
},
},
},
自定义指令传值:
main.js中:
/*
全局自定义指令传值
*/
Vue.directive("pinkColor", {
inserted(el, binding) {
el.style.color = binding.value;
},
});
自己vue文件中:
注意:传的值是字符串还是变量
① 字符串用法:
<template>
<div>
<div>
<h2>全局指令传值</h2>
<!-- v-pinkColor="'pink'" 注意是字符串 -->
<p v-pinkColor="'pink'">全局指令传值</p>
</div>
</div>
</template>
② 变量用法
<template>
<div>
<div>
<p v-pinkColor="colorStr">全局自定义指令传值变量用法</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
colorStr: "pink",
};
}
};
</script>