创建一个文件来管理所有的自定义指令
src/directives/index.js
在src/directives/index.js文件中定义几个指令
javascript">//改变文字颜色指令
export const fontColor={
//dom元素节点 options包含传入的属性对象
inserted(dom,options){
dom.style.background=options.value
}
}
// 改变文字大小指令
export const fontSize = {
inserted(dom) {
dom.style.fontSize = '24px'
}
}
js_22">在main.js中完成全局注册
javascript">//import * as 变量 得到的是一个对象{ 变量1:对象1,变量2: 对象2 }
//这里得到的是 {fontColor:Object,fontSize:Object}
import * as directives from '@/directives'
// Object.keys 方法返回一个对象键名的数组
Object.keys(directives).forEach(key => {
// 注册自定义指令
Vue.directive(key, directives[key])
})
使用
javascript"><template>
<span v-fontColor="color" v-fontSize class="name">改变文字颜色和大小</span>
</template>
<script>
export default {
data() {
return {
color: 'skyblue'
}
},
}
</script>