vue 自定义指令
全局注册
const app = Vue.createApp({})
// 注册一个全局自定义指令 `v-focus`
app.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
mounted(el) {
// Focus the element
el.focus()
}
})
局部注册
data(){
return {}
},
directives:{
focus: {
mounted(el, binding) {
console.log(el);
console.log(binding);
el.style.position = 'fixed'
// binding.arg is an argument we pass to directive
const s = binding.arg || 'top'
el.style[s] = binding.value + 'px'
}
}
},
模板中使用
<button v-focus:[direction]="200">aaa</button>//direction等下介绍
钩子函数
import { createApp } from 'vue'
const app = createApp({})
// 注册
app.directive('my-directive', {
// 指令是具有一组生命周期的钩子:
// 在绑定元素的父组件挂载之前调用
beforeMount() {},
// 绑定元素的父组件挂载时调用
mounted() {},
// 在包含组件的 VNode 更新之前调用
beforeUpdate() {},
// 在包含组件的 VNode 及其子组件的 VNode 更新之后调用
updated() {},
// 在绑定元素的父组件卸载之前调用
beforeUnmount() {},
// 卸载绑定元素的父组件时调用
unmounted() {}
})
// 注册 (功能指令)
app.directive('my-directive', () => {
// 力扣 – 中文网 助你高效提升编程技能 https://www.javascriptc.com/special/leetcode/
// 这将被作为 `mounted` 和 `updated` 调用 在局部注册也一样使用箭头函数就代表默认mounted或者updated
})
// getter, 如果已注册,则返回指令定义
const myDirective = app.directive('my-directive')
钩子函数的参数
el
指令绑定到的元素。这可用于直接操作 DOM。
binding
instance:使用指令的组件实例。
value:传递给指令的值。例如,在 v-my-directive=“1 + 1” 中,该值为 2。
oldValue:先前的值,仅在 beforeUpdate 和 updated 中可用。值是否已更改都可用。
arg:参数传递给指令 (如果有)。例如在 v-my-directive:foo 中,arg 为 “foo”。
modifiers:包含修饰符 (如果有) 的对象。例如在 v-my-directive.foo.bar 中,修饰符对象为 {foo: true,bar: true}。
dir:一个对象,在注册指令时作为参数传递。例如,在以下指令中
dir
app.directive(‘focus’, {
mounted(el) {
el.focus()
}
})
dir将是以下对象
{
mounted(el) {
el.focus()
}
}
vnode
上面作为 el 参数收到的真实 DOM 元素的蓝图。
prevNode
上一个虚拟节点,仅在 beforeUpdate 和 updated 钩子中可用。
注意:除了 el 之外,你应该将这些参数视为只读,并且永远不要修改它们。如果你需要跨钩子共享信息,建议通过元素的自定义数据属性集 (opens new window)进行共享。
动态指令参数
<button v-focus:[direction]="200">aaa</button>
//此时这里的direction和200都可以使用组件data中定义的属性
函数简写
app.directive('pin', (el, binding) => {
el.style.position = 'fixed'
const s = binding.arg || 'top'
el.style[s] = binding.value + 'px'
}) //此时只在钩子函数mounted和updated里面起作用