在组件外
在一个js文件中定义
import Vue from 'vue'
const color = Vue.directive('color',{
//不需要属性的指令
// inserted(el){
// console.log(el)
// el.style.color = 'red'
// }
//需要属性的指令
bind(el,binding){
switch(binding.value){
case 'red':
el.style.color = 'red'
break;
case 'blue':
el.style.color = 'blue'
break;
}
}
})
export default color
在main.js中全局引用
import '@/api/color'
在父组件中使用
<div v-color>浙江省杭州市</div> //字体为红色
<div v-color="'blue'">浙江省杭州市</div> //字体为蓝色
在组件内定义
directives:{
background:{
inserted(el){
el.style.background='yellow'
}
}
},
在父组件中使用
<div v-color="'blue'" v-background>浙江省杭州市</div>