一、Vue2与Vue3自定义指令对比。
Vue2 | Vue3 | |
created(新增) | ||
bind | beforeMount | |
inserted | mounted | |
update (Vue3弃用) | beforeUpdate(新增) | |
componentUpdated | updated | |
beforeUnmount(新增) | ||
unbind | unmounted |
二、写法。
1.没有使用<script setup>
export default {
setup() {
/*...*/
},
directives: {
// 在模板中启用 v-focus
focus: {
/* ... */
}
}
}
2.自定义指令全局注册
const app = createApp({})
// 使 v-focus 在所有组件中都可用
app.directive('focus', {
/* ... */
})
三、指令钩子
const myDirective = {
// 在绑定元素的 attribute 前
// 或事件监听器应用前调用
created(el, binding, vnode, prevVnode) {},
// 在元素被插入到 DOM 前调用
beforeMount(el, binding, vnode, prevVnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都挂载完成后调用
mounted(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件更新前调用
beforeUpdate(el, binding, vnode, prevVnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都更新后调用
updated(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件卸载前调用
beforeUnmount(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件卸载后调用
unmounted(el, binding, vnode, prevVnode) {}
}
四、钩子参数。
el
:指令绑定到的元素。这可以用于直接操作 DOMbinding
:一个对象,包含(value, oldValue, arg, modifiers, instance, dir)属性。value
:传递给指令的值。例如在v-my-directive="1 + 1"
中,值是2
。oldValue
:之前的值,仅在beforeUpdate
和updated
中可用。无论值是否更改,它都可用。arg
:传递给指令的参数 (如果有的话)。例如在v-my-directive:foo
中,参数是"foo"
。modifiers
:一个包含修饰符的对象 (如果有的话)。例如在v-my-directive.foo.bar
中,修饰符对象是{ foo: true, bar: true }
。instance
:使用该指令的组件实例。-
vnode
:代表绑定元素的底层 VNode。 -
prevNode
:代表之前的渲染中指令所绑定元素的 VNode。仅在beforeUpdate
和updated
钩子中可用。
案例:
let color = ref('red')
.....
<div v-example:foo.bar="color">
五、简化写法。
对于自定义指令来说,一个很常见的情况是仅仅需要在 mounted
和 updated
上实现相同的行为,除此之外并不需要其他钩子。这种情况下我们可以直接用一个函数来定义指令,如下所示:
<div v-color="color"></div>
......
app.directive('color', (el, binding) => {
// 这会在 `mounted` 和 `updated` 时都调用
el.style.color = binding.value
})
六、对象字面量。
如果你的指令需要多个值,你可以向它传递一个 JavaScript 对象字面量。别忘了,指令也可以接收任何合法的 JavaScript 表达式。
<div v-demo="{ color: 'white', text: 'hello!' }"></div>
......
app.directive('demo', (el, binding) => {
console.log(binding.value.color) // => "white"
console.log(binding.value.text) // => "hello!"
})
七、组件上使用。
当在组件上使用自定义指令时,它会始终应用于组件的根节点,和透传 attributes 类似。
<MyComponent v-demo="test" />
<!-- MyComponent 的模板 -->
<div> <!-- v-demo 指令会被应用在此处 -->
<span>My component content</span>
</div>
注意:组件可能含有多个根节点。当应用到一个多根组件时,指令将会被忽略且抛出一个警告。和 attribute 不同,指令不能通过 v-bind="$attrs"
来传递给一个不同的元素。总的来说,不推荐在组件上使用自定义指令。
八、案例
节流和防抖自定义指令
export const shake = (el, binding) => {
let { value, arg } = binding
console.log(value, arg)
let timer = null
el.addEventListener('input', () => {
clearTimeout(timer)
timer = setTimeout(() => {
value()
}, arg || 500)
})
}
export const throttle = (el, binding) => {
let { value, arg } = binding
console.log(value, arg)
let lastExecTime = 0
el.addEventListener('click', () => {
if(Date.now() - lastExecTime > arg || !arg){
value()
lastExecTime = Date.now()
}
})
}
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { shake, throttle } from './utils/directive'
const app = createApp(App)
// 使 v-focus 在所有组件中都可用
app.directive('color', (el, binding) => {
//console.log(binding) // => "foo"
})
app.directive('example', (el, binding) => {
//console.log(binding)
})
app.directive('shake', shake)
app.directive('throttle', throttle)
app.mount('#app')
<script setup>
import { ref } from 'vue'
let color = ref('red')
const handler = () => {
console.log(color.value)
}
const throttleHandler = () => {
console.log('节流函数')
}
</script>
<template>
<!-- <div class="container" v-color:foo="color"></div>
<div v-example:foo.bar="color"></div> -->
<input type="text" v-model="color" v-shake:500="handler"/>
<button class="btn-throttle" v-throttle:500="throttleHandler">节流函数</button>
</template>
<style scoped>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.btn-throttle{
margin: 20px;
&:hover{
cursor: pointer;
}
}
</style>