*vue2有13种指令: v-once v-bind v-model v-if 等当这几种指令不满足自己的使用的时候可以自定义指令的vue2指令的钩子 bind insert update component Updated unbind
vue3的指令和vue2的不一致**
1.vue3的指令的钩子函数:
**created 元素初始化的时候
beforeMount指令绑定到元素后调用 只调用一次
Mounted元素插入父级Do'm调用
beforeUpdate 元素被更新之前调用
updated 在包含组件的 VNode 及其子组件的 VNode 更新后调用
beforeUnmount在元素被移除前调用
unmounted指令被移除后调用 只调用一次**
vue3的setup语法糖写法
directi.vue
<template>
<div class="dire">
A
</div>
</template>
<script setup lang="ts">
</script>
<style scoped>
.dire{
width:200px;height: 200px;border: 1px solid #000;
}
</style>
<template>
<div>
<directi v-if="flag" v-move="{background:'red',flag:flag}"></directi>
//测试更新钩子
<!--<directi v-move="{background:'red',flag:flag}"></directi>-->
</div>
</template>
<script setup>
import {ref} from 'vue'
import directi from './components/directi.vue'
const flag=ref(true)
const vMove={
// 初始化加载下面3
created() {
console.log('created')
},
beforeMount() {
console.log('beforeMount')
},
mounted(el,dir) {
console.log('mounted',dir.value.background)
el.style.background=dir.value.background;
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated(){
console.log('updated')
},
// 销毁触发下面2
beforeUnmount(){
console.log('beforeUnmount')
},
unmounted(){
console.log('unmounted')
}
}
</script>
<style scoped>
</style>
VUE3+ts写法:
<template>
<div>
<button @click="flag=!flag">切换</button>
//测试显示隐藏触发的钩子
<directi v-if="flag" v-move:aaa.xiaozhu="{background:'red',flag:flag}"></directi>
// 测试更新触发的钩子
<!-- <directi v-move="{background:'red',flag:flag}"></directi> -->
</div>
</template>
<script setup lang="ts">
import {ref,Directive, DirectiveBinding} from 'vue'
import directi from './components/directi.vue'
const flag=ref<Boolean>(true);
type Dir={
background:string
}
const vMove:Directive={
// 初始化加载下面3
created() {
console.log('created')
},
beforeMount() {
console.log('beforeMount')
},
mounted(el:HTMLElement,dir:DirectiveBinding<Dir>) {
console.log('mounted',dir.value.background)
el.style.background=dir.value.background;
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated(){
console.log('updated')
},
// 销毁触发下面2
beforeUnmount(){
console.log('beforeUnmount')
},
unmounted(){
console.log('unmounted')
}
}
</script>
<style scoped>
</style>
自定义指令函数简写:
<template>
<div>
<button @click="flag=!flag">切换</button>
//测试显示隐藏触发的钩子
<directi v-if="flag" v-move:aaa.xiaozhu="{background:'red',flag:flag}"></directi>
// 测试更新触发的钩子
<!-- <directi v-move="{background:'red',flag:flag}"></directi> -->
</div>
</template>
<script setup lang="ts">
import {ref,Directive, DirectiveBinding} from 'vue'
import directi from './components/directi.vue'
const flag=ref<Boolean>(true);
type Dir={
background:string
}
const vMove:Directive=(el:HTMLElement,bingding:DirectiveBinding<Dir>)=>{
el.style.background=bingding.value.background
}
</script>
<style scoped>
</style>