一个自定义指令由一个包含类似组件生命周期钩子的对象来定义。钩子函数会接收到指令所绑定元素作为其参数。
页面内创建自定义指令
下面是一个自定义指令的例子,当一个 input 元素被 Vue 插入到 DOM 中后,它会被自动聚焦:
<script setup>
// 在模板中启用 v-focus
const vFocus = {
mounted: (el) => el.focus() //使input自动聚焦
//el.querySelector('input').focus() //使el-input自动聚焦
}
</script>
<template>
<input v-focus />
</template>
创建全局自定义指令
在main.js中进行全局挂载
const app = createApp({})
// 使 v-focus 在所有组件中都可用
app.directive('focus', {
mounted: (el) => el.querySelector('input').focus() //使el-input自动聚焦 所有页面都可使用 v-focus使用
})
项目中使用 vue3
在日常项目中我们不会直接在main.js中写自定义指令,因为一个项目中可能存在多个自定义指令,直接写在main.ts会非常的乱,多,所以我们通常会创建一个directive.js在里边定义多个指令,在main.js引入注册即可
directive.js
import type { App } from 'vue'
import Waves from 'node-waves'
import 'node-waves/dist/waves.min.css'
export default function directive(app: App) {
// 注册 v-auth
app.directive('auth', {
mounted: (el, binding) => {
if (!useAuth().auth(binding.value)) {
el.remove()
}
},
})
app.directive('timeago', {
mounted: (el, binding) => {
el.innerText = useTimeago().format(binding.value)
if (binding.modifiers.interval) {
el.__timeagoSetInterval__ = setInterval(() => {
el.innerText = useTimeago().format(binding.value)
}, 1000)
}
},
beforeUnmount: (el, binding) => {
if (binding.modifiers.interval) {
clearInterval(el.__timeagoSetInterval__)
}
},
})
// 注册 Waves 指令
app.directive('waves', {
created: () => {
Waves.init()
},
mounted: (el, binding) => {
const classes = ['button', 'circle', 'block', 'float', 'light', 'classic'].filter(cls => binding.modifiers[cls]).map(cls => `waves-${cls}`)
Waves.attach(el, classes)
},
})
}
main.js引入挂载
// 自定义指令
import directive from '@/utils/directive'
directive(app)
页面使用
<el-button type="primary" :icon="Download" v-auth="'data:zoneItemStatistics:export'"
@click="downloadexport">导出</el-button>
指令钩子
一个指令的定义对象可以提供几种钩子函数 (都是可选的):
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
:指令绑定到的元素。这可以用于直接操作 DOM。 -
binding
:一个对象,包含以下属性。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
:使用该指令的组件实例。dir
:指令的定义对象。
-
vnode
:代表绑定元素的底层 VNode。 -
prevNode
:代表之前的渲染中指令所绑定元素的 VNode。仅在beforeUpdate
和updated
钩子中可用。