1. 什么是自定义指令
vue 官方提供了v-text、v-for、v-model、v-if 等常用的指令。除此之外vue 还允许开发者自定义指令。
2. 自定义指令的分类
vue 中的自定义指令分为两类,分别是:
3. 私有自定义指令
在每个vue 组件中,可以在directives 节点下声明私有自定义指令。示例代码如下:
4. 使用自定义指令
在使用自定义指令时,需要加上v- 前缀。示例代码如下:
5. 为自定义指令动态绑定参数值
在 template 结构中使用自定义指令时,可以通过等号(=)的方式,为当前指令动态绑定参数值:
6. 通过 binding 获取指令的参数值
在声明自定义指令时,可以通过形参中的第二个参数,来接收指令的参数值:
7. update 函数
bind 函数只调用 1 次:当指令第一次绑定到元素时调用,当 DOM 更新时bind 函数不会被触发。 update 函 数会在每次 DOM 更新时被调用。示例代码如下:
8. 函数简写
如果 bind 和update 函数中的逻辑完全相同,则对象格式的自定义指令可以简写成函数格式:
9. 全局自定义指令
全局共享的自定义指令需要通过“Vue.directive()”进行声明,示例代码如下:
10. vue自定义指令的代码示例
// 私有自定义指令的节点
directives: {
// 定义名为 color 的指令,指向一个配置对象
/* color: {
// 当指令第一次被绑定到元素上的时候,会立即触发 bind 函数
// 形参中的 el 表示当前指令所绑定到的那个 DOM 对象
bind(el, binding) {
console.log('触发了 v-color 的 bind 函数')
el.style.color = binding.value
},
// 在 DOM 更新的时候,会触发 update 函数
update(el, binding) {
console.log('触发了 v-color 的 update 函数')
el.style.color = binding.value
}
} */
color(el, binding) {
el.style.color = binding.value
}
}
11. Main.js文件中 Vue.config.productionTip 意义
提示开发模式和发布(生产)模式,本行代码无意义
Vue.config.productionTip = false
值为 True 或 False 表示能否看到如下的提示
等于true(或默认不写)的显示(如上图),会提示处在的模式
等于False的显示(如上图),没有提示处于什么模式
总结:
① 能够掌握 keep-alive 元素的基本使用
<keep-alive> 标签、 include 属性② 能够掌握插槽的基本用
<slot> 标签、具名插槽、 作 用 域 插 槽 、 后备 内 容③ 能够知道如何自定义指令
私有自定义指 令 directives: { }全局自定义指 令 Vue.directive()