1 概述
简介:除了核心功能默认内置的指令 (v-model, v-show 等),Vue 也允许注册自定义指令。
场景:
注意,在 Vue2.x 中,代码复用和抽象的主要形式是组件。
然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。
2 语法-示例
举个聚焦输入框的例子;
期望结果:页面打开时,input 自动获得焦点。
拓展:表单的 autofocus 属性 在移动端的 Safari 上不工作。
全局注册 “自定义指令”
Vue.directive()
指令配置项 & 配置项参数;
局部注册 “自定义指令”
directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
}
tip: 配置项和钩子参数同上面 全局自定义指令的参数。
使用:可以在模板中任何元素上使用新的 v-focus property。
<input v-focus />
3 动态指令参数
语法:
<p v-pin:[direction]="200">Stick me 200px from the top of the page</p>
4 函数简写
// 简化前(配置项)
Vue.directive('color-swatch', {
inserted: function (el, binding) {
/* ... */
},
})
// 简化后(直接的函数)
Vue.directive('color-swatch', function (el, binding) {
el.style.backgroundColor = binding.value
})
5 指令绑定值为 对象字面量
如果指令需要多个值,可以传入一个 JS 对象字面量。
记住,指令函数能够接受所有合法的 JS 表达式。
<div v-demo="{ color: 'white', text: 'hello!' }"></div>
Vue.directive('demo', function (el, binding) {
console.log(binding.value.color) // => "white"
console.log(binding.value.text) // => "hello!"
})