1、什么是自定义指令
- vue 官方提供了 v-text、v-for、v-model、v-if 等常用的指令。除此之外 vue 还允许开发者自定义指令
2、自定义指令的分类
- vue 中的自定义指令分为两类,分别是:
- 私有自定义指令
- 全局自定义指令
3、 私有自定义指令
-
在每个 vue 组件中,可以在 directives 节点下声明私有自定义指令
-
使用私有指令时,要加上v-前缀
-
动态绑定参数值
-
通过binding获取指令的参数
-
update函数:
- bind 函数只调用 1 次:当指令第一次绑定到元素时调用,当 DOM 更新时 bind 函数不会被触发。 update 函数会在每次 DOM 更新时被调用
-
如果 insert 和update 函数中的逻辑完全相同,则对象格式的自定义指令可以简写成函数格式
<template>
<div class="app-container">
<h1 v-color="color">App 根组件</h1>
<button @click="color = 'blue'">点击切换App颜色</button>
<hr />
<Article> </Article>
<hr />
<div class="box" style="display: none">
<!-- 渲染 Left 组件和 Right 组件 -->
<Left>
<template v-slot:default>
<p>这是Left组件中的p标签</p>
</template>
</Left>
</div>
</div>
</template>
<script>
import Left from "@/components/Left.vue";
import Right from "@/components/Right.vue";
import Article from "@/components/Article.vue";
export default {
components: {
Left,
Right,
Article,
},
data() {
return {
comName: "Left",
color: "lightsalmon",
};
},
// 定义私有自定义指令
directives: {
// color: {
// 当指令被第一次绑定到元素上的时候,会触发bind函数
// bind(el, binding) {
// // el: 表示被绑定的DOM元素对象
// el.style.color = binding.value;
// },
// 每次DOM更新时都会被调用
// update(el, binding) {
// el.style.color = binding.value;
// },
// },
// 如果bind和update函数处理的逻辑完全相同,则可以简写
color(el, binding) {
el.style.color = binding.value;
},
},
};
</script>
<style lang="less">
.app-container {
padding: 1px 20px 20px;
background-color: #efefef;
}
.box {
display: flex;
}
</style>
4、全局自定义指令
- 全局共享的自定义指令需要通过“Vue.directive()”进行声明
- 在main.js中进行声明
Vue.directive('color', function (el, binding) {
el.style.color = binding.value;
})