简言
除了 Vue 内置的一系列指令 (比如 v-model 或 v-show) 之外,Vue 还允许你注册自定义的指令 (Custom Directives)。
官网自定义指令
我们已经介绍了两种在 Vue 中重用代码的方式:组件和组合式函数。组件是主要的构建模块,而组合式函数则侧重于有状态的逻辑。另一方面,自定义指令主要是为了重用涉及普通元素的底层 DOM 访问的逻辑。
今天我们来学习使用下自定义指令。
话不多说,不玩虚的,这就4vue,莱茨狗! ——ZSK666
使用
注册方式
- 全局注册。vue实例使用directive(指令名,指令对象)方法全局注册自定义指令,注册后整个实例的组件都可用。在模板中v-指令名使用
<div v-color="color"></div>
app.directive('color', (el, binding) => {
// 这会在 `mounted` 和 `updated` 时都调用
el.style.color = binding.value
})
- 局部注册。选项式使用directives预设对象局部注册自定义使用,注册后这个组件可以用。组合式不需要显示注册,命名时必须遵循 vNameOfDirective 这样的命名规范,就是名字前带v
const focus = {
mounted: (el) => el.focus()
}
// 选项式
export default {
directives: {
// 在模板中启用 v-focus
focus
}
}
<script setup>
// 组合式
const vMyDirective = {
beforeMount: (el) => {
// 在元素上做些操作
}
}
</script>
<template>
<h1 v-my-directive>This is a Heading</h1>
</template>
钩子函数
一个指令的定义对象可以提供几种钩子函数 (都是可选的):
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 钩子中可用。
例如:
<div v-example:foo.bar="baz">
binding 参数会是一个这样的对象:
{
arg: 'foo',
modifiers: { bar: true },
value: /* `baz` 的值 */,
oldValue: /* 上一次更新时 `baz` 的值 */
}
使用示例
这里我了一个自定义指令,给使用它的元素添加鼠标移入效果。
- 创建自定义指令对象:
/*
* @Date: 2022-11-16 15:01:16
* @LastEditors: zhangsk
* @LastEditTime: 2022-11-16 16:18:56
* @FilePath: \basic-demo\src\utils\moveEnter.ts
* @Label: Do not edit
*/
import type { DirectiveBinding, VNode } from "vue";
let enterTime = 0
let leaveTime = 0
const moveEnter = {
// 在绑定元素的 attribute 前
// 或事件监听器应用前调用
created(el: Element, binding: DirectiveBinding, vnode: VNode, prevVnode: VNode | null) {
// 下面会介绍各个参数的细节
console.log(el, binding, vnode, prevVnode);
},
// 在元素被插入到 DOM 前调用
beforeMount(el: any, binding: any, vnode: any, prevVnode: any) { },
// 在绑定元素的父组件
// 及他自己的所有子节点都挂载完成后调用
mounted(el: Element, binding: DirectiveBinding) {
el.addEventListener('mouseenter', (e: Event) => {
enterTime = new Date().getTime()
// 加入全局定义的move-enter
el.classList.add('move-enter')
})
el.addEventListener('mouseleave', (e: Event) => {
leaveTime = new Date().getTime()
let timer: any = null
if ((leaveTime - enterTime) > 1000) {
el.classList.remove('move-enter')
} else {
timer = setTimeout(() => {
el.classList.remove('move-enter')
clearTimeout(timer)
}, 1000)
}
})
},
// 绑定元素的父组件更新前调用
beforeUpdate(el: any, binding: any, vnode: any, prevVnode: any) { },
// 在绑定元素的父组件
// 及他自己的所有子节点都更新后调用
updated(el: any, binding: any, vnode: any, prevVnode: any) { },
// 绑定元素的父组件卸载前调用
beforeUnmount(el: any, binding: any, vnode: any, prevVnode: any) {
console.log('要注销');
el.removeEventListener('mouseenter')
el.removeEventListener('mouseleave')
},
// 绑定元素的父组件卸载后调用
unmounted(el: any, binding: any, vnode: any, prevVnode: any) { }
}
export default moveEnter
由于使用了class类,我们也得全局使用class类,我这里写在了assets/css/main.scss下,你也可以自己创建一个css文件然后再main.ts引入,总之能够生效就行。
.move-enter {
position: relative;
background-color: #000 !important;
color: #fff !important;
box-shadow: 10px 10px 10px rgb(128, 127, 127) !important;
animation-name: identifier;
animation-duration: 1s;
}
@keyframes identifier {
0% {
left: 0;
}
50% {
left: 10px;
}
100% {
left: 0;
}
}
- 全局注册自定义指令
在main.ts中注册
/*
* @Date: 2022-10-27 11:31:17
* @LastEditors: zhangsk
* @LastEditTime: 2022-11-16 15:09:51
* @FilePath: \basic-demo\src\main.ts
* @Label: Do not edit
*/
import { createApp } from 'vue'
import App from './App.vue'
// router
import router from './router/index'
// 自定义指令
import moveEnter from './utils/moveEnter'
// vue实例
const app = createApp(App)
app.use(router)
app.mount('#app')
app.directive('move-enter', moveEnter)
- 组件中使用
新建一个文件并使用,使用了vueRouter的同学别忘了在router里配置路由,配置方法:学习使用vueRouter
<!--
* @Date: 2022-11-16 15:10:41
* @LastEditors: zhangsk
* @LastEditTime: 2022-11-16 16:21:31
* @FilePath: \basic-demo\src\pages\two\index.vue
* @Label: Do not edit
-->
<template>
<div class="two">
<h1>two</h1>
<div class="main">
<div class="div" v-move-enter:foo="'hhh'">这是一个div0</div>
<div class="div" v-for="item of 8" v-move-enter>
这是一个div{{ item }}
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import { reactive, toRefs, onBeforeMount, onMounted } from "vue";
</script>
<style lang="scss" scoped>
.two {
position: relative;
.main {
// display: flex;
// justify-content: space-around;
}
}
.div {
display: inline-block;
width: 200px;
height: 400px;
line-height: 400px;
text-align: center;
background-color: #fff;
border-radius: 20px;
border: 2px solid #eaeaea;
cursor: pointer;
}
</style>
- 效果
结语
结束了。我这里只是简单使用了下自定义指令,并没有涉及到bindding参数,利用bingding参数可以实现更加多样的效果。另外这有个bug,移入后立马快速移出,再快速移入,会发现移入效果不起作用,这是因为,移除class之前你再次移入将不会添加class。提供一种解决思路,这里可以用dataset(就是原生dom可以自定义以data-开头的数据,会放在dom的dataset里面)记录是正在执行移除操作,是的话取消移除操作。