除了核心功能默认内置的指令 (v-model
和 v-show
),Vue 也允许注册自定义指令。 v-xxx
- 局部注册及使用
- 局部注册只能在当前组件中使用
<template>
<div>
<input type="text" v-focus />
</div>
</template>
<script>
export default {
// 局部注册
directives: {
focus: { // 自定义指令名
inserted(el){ // 固定配置项 - 当指令插入到标签自动触发此函数
//el为当前挂载命令的dom对象
el.focus()
}
},
},
};
</script>
全局注册
- 在main.js用 Vue.directive()方法来进行注册, 以后随便哪个.vue文件里都可以直接用v-fofo指令
Vue.directive("fofo", {
inserted(el){
el.focus()
}
})
自定义指令-接值
- 定义color指令-传入一个颜色, 给标签设置文字颜色
Vue.directive("color", {
inserted(el, binding){ // 插入时触发此函数
el.style.color = binding.value;
},
update(el, binding){ // 更新时触发此函数
el.style.color = binding.value;
}
})
<p v-color="theColor" @click="changeColor">使用v-color指令控制颜色, 点击变蓝</p>
<script>
data() {
return {
theColor: "red",
};
},
methods: {
changeColor() {
this.theColor = 'blue';
},
},
</script>
总结: v-xxx, 自定义指令, 获取原生DOM, 自定义操作