vue的自定义指令
<template>
<!--
自定义指令可以包含以下钩子函数:
- created:元素初始化的时候
- beforeMount:指令绑定到元素后调用 只调用一次
- mounted:元素插入父级dom调用
- beforeUpdate:元素被更新之前调用
- updated:这个周期方法被移除
- beforeUnmount:在元素被移除前调用
- unmounted:指令被移除后调用 只调用一次
每一个钩子函数都可以指定两个参数,一个 el,另一个是 binding
- el:指令所绑定的元素,可以用来直接操作 DOM。
- binding:一个对象,包含以下属性:
- instance:使用指令的组件实例。
- 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 }`。
- dir:一个对象,在注册指令时作为参数传递。例如在以下指令中
自定义指令可以接收参数,通过对象的方式
除了可以接收参数外,还可以接收修饰符,通过在自定义指令后以 . 开头的名称,如下例中的 .jock 就是一个修饰符,它在 binding.modifiers 中可以获取到
-->
<div class="container">
<p v-move.jock="{ flag: flag} ">自定义指令</p>
<button @click="flag = !flag">切换 -- {{ flag }}</button>
</div>
</template>
<script setup lang="ts">
import {Directive, DirectiveBinding, ref} from 'vue'
const flag = ref<boolean>(true)
const vMove: Directive = {
created() {
console.log('created.......')
},
beforeMount() {
console.log('beforeMount.....');
},
mounted(el: HTMLElement, binding: DirectiveBinding) {
console.log('mounted.....');
console.log(binding);
console.log(binding.modifiers);
},
beforeUpdate() {
console.log('beforeUpdate......');
},
updated(el: HTMLElement, binding: DirectiveBinding) {
console.log('updated......');
console.log(binding.oldValue, binding.value);
},
beforeUnmount() {
console.log('beforeUnmount......');
},
unmounted() {
console.log('unmounted.....');
}
}
</script>
<style scoped>
.container {
width: 300px;
height: 300px;
border: 1px solid #CCCCCC;
}
</style>
vue的自定义指令简写
<template>
<!--
自定义指令的简写方式,因为在真正的开发中,我们用得最多的还是 mounted 和 updated 这两个钩子函数,其它的用得非常少。
下面以通过自定义指定来修改背景颜色为例来演示
-->
<p><input type="text" v-model="color" placeholder="输入要显示的颜色名称"></p>
<div class="container" v-move="{ background: color }"></div>
</template>
<script setup lang="ts">
import {Directive, DirectiveBinding, ref} from 'vue'
const color = ref<string>('')
const vMove: Directive = (el: HTMLElement, binding: DirectiveBinding) => {
el.style.backgroundColor = binding.value.background
}
</script>
<style scoped>
.container {
width: 300px;
height: 300px;
border: 1px solid #CCCCCC;
}
</style>