0%

vue自定义指令

自定义指令

Vue 除了默认的内置指令, 还允许注册自定义指令.

全局注册

1
2
3
4
5
6
7
// 注册 v-focus 自定义指令
Vue.directive('focus', {
inserted(el) {
// 自动获取焦点
el.focus()
}
})

局部注册

1
2
3
4
5
6
7
8
9
10
new Vue({
el: '#app',
directives: {
focus: {
inserted: function(el) {
el.focus()
}
}
}
})

使用 v-focus 自定义指令

1
<input v-focus />

钩子函数

一个指令定义对象可以提供几个钩子函数

  • bind: 只调用一次, 指令第一次绑定到元素时调用, 可以进行一次性的初始化设置
  • inserted: 被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
  • update: 所在组件的 VNode 更新时调用, 但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新
  • componentUpdated: 指令所在组件的 VNode 及其子 VNode 全部更新后调用
  • unbind: 只调用一次, 指令与元素解绑时调用

钩子函数的参数

  • el: 指令所绑定的元素, 可以用来直接操作 DOM
  • binding: 一个对象, 包含以下属性:
    • name: 指令名, 不包括v-前缀
    • value: 指令的绑定值, 例: v-my-directive="1+1", value 为 2
    • oldvalue: 指令绑定的前一个值, 仅在 updatecomponentUpdate 钩子中可用
    • expression: 字符串形式的指令表达式, 例: v-my-directive="1+1", 表达式为 “1+1”
    • arg: 传给指令的参数, 可选. 例: v-my-directive:foo, arg 为 foo
    • modifiers: 一个包含修饰符的对象, 例: v-my-directive:foo.bar, 修饰符对象为 { foo: true, bar : true}
  • vnode: Vue 编译生成的虚拟节点
  • oldVnode: 上一个虚拟节点, 仅在 updatecomponentUpdate 钩子可用

除了 el, 其他参数都应该是只读的, 切勿修改, 如果要在钩子之间共享数据, 建议通过元素的 dataset 来进行

动态指令参数

指令的参数可以是动态的, 例 v-my-directive:[argument]="value", argument 参数可以根据组件数据进行更新

1
2
3
4
<div id="baseexample">
<p>Scroll down the page</p>
<p v-pin="200">Stick me 200px from the top of the page</p>
</div>
1
2
3
4
5
6
7
8
9
10
Vue.directive('pin', {
bind: function(el, binding, vnode) {
el.style.position = 'fixed'
el.style.top = binding.value + 'px'
}
})

new Vue({
el: 'baseexample'
})

这会把该元素固定在距离页面顶部 200 像素的位置。但如果场景是我们需要把元素固定在左侧而不是顶部又该怎么办呢?这时使用动态参数就可以非常方便地根据每个组件实例来进行更新。

1
2
3
4
<div id="dynamicexample">
<h3>Scroll down inside this section ↓</h3>
<p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Vue.directive('pin', {
bind: function(el, binding, vnode) {
el.style.position = 'fixed'
var s = binding.arg == 'left' ? 'left' : 'top'
el.style[s] = binding.value + 'px'
}
})

new Vue({
el: '#dynamicexample',
data: function() {
return {
direction: 'left'
}
}
})

函数简写

在很多时候,你可能想在 bind 和 update 时触发相同行为,而不关心其它的钩子。比如这样写:

1
2
3
Vue.directive('color-swatch', function(el, binding) {
el.style.backgroundColor = binding.value
})

对象字面量

如果指令需要多个值,可以传入一个 JavaScript 对象字面量。记住,指令函数能够接受所有合法的 JavaScript 表达式。

1
<div v-demo="{ color: 'white', text: 'hello!' }"></div>
1
2
3
4
Vue.directive('demo', function(el, binding) {
console.log(binding.value.color) // => "white"
console.log(binding.value.text) // => "hello!"
})
请作者喝杯咖啡