一、全局定义
Vue.directive()
参数:
- 指令的名字(定义的时候不加v-,使用vue指令的时候加上v-)
- 对象,里面包含三个钩子方法
bind 只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置
inserted 这个元素已经渲染到界面上之后执行
update 当元素有更新的时候执行
这三个钩子方法的参数
1、el:指令所绑定的元素,可以用来直接操作 DOM 。
2、binding:一个对象,包含以下属性:
(1)name:指令名,不包括 v- 前缀。
(2)value:指令的绑定值。
(3)oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated钩子中可用。
<div id="app">
<p v-color="">{{msg}}</p>
<p v-color="myColor">{{msg}}</p>
<p v-color="'green'">{{msg}}</p>
</div>
// 全局定义
Vue.directive("color", {
bind(el, bind) {
// el.style.color='red'
el.style.color = bind.value;
},
inserted(el) {
el.style.fontSize = "20px";
},
update(el) {
// 不触发
el.style.fontWeight = "700";
},
});
let vm = new Vue({
el: "#app",
data: {
msg: "我是标签的内容",
myColor: "blue",
},
methods: {},
});
二、私有定义
directives
作为属性和el、data、methods同级,该属性是一个对象
对象键就是指令的名字,后面的对象就是指令的内容
简写直接写一个函数,函数名就是指令的名字。
let vm2 = new Vue({
el: "#app2",
data: {
msg: "我是标签的内容",
myColor: "blue",
},
methods: {},
// 私有定义 directives属性,和el、data、methods同级
directives: {
color2(el,bind){
el.style.color=bind.value
},
// 另一种写法
color2: {
bind(el, bind) {
el.style.color = bind.value;
},
inserted(el) {
el.style.fontSize = "30px";
},
update(el) {
// 不触发
el.style.fontWeight = "700";
},
},
},
});