-
1.Vue自定义指令原理:
Vue自定义指令原理涉及到vue的指令系统和生命周期钩子函数,当你在vue中使用自定义指令的时候,实际上就是通过vue的指令系统将指令绑定到对应的Dom元素上,并在指令的生命周期内进行相应的操作。
Vue自定义指令允许注册全局自定义指令跟局部自定义指令
2.Vue3.0的全局自定义指令:
//在main.ts中全局注册
import { createApp } from 'vue'
const app = createApp(App)
app.directive('my-directive', {
beforeMount(el, binding, vnode, prevVnode) {
// 指令绑定时的操作
},
mounted(el, binding, vnode, prevVnode) {
// 指令绑定到元素后的操作
},
beforeUnmount(el, binding, vnode, prevVnode) {
// 指令与元素解绑前的操作
},
unmounted(el, binding, vnode, prevVnode) {
// 指令与元素解绑后的操作
}
})
//在组件内使用
<template>
<div v-my-directive></div>
</template>
3.Vue3.0的局部自定义指令
<template>
<img v-imgerror="imgerror" :src="imgSrc" alt="">
</template>
<script lang="ts" setup>
//用自定义指令做一个没有图片的话出现图裂效果
import {ref} from 'vue'
//原照片地址
const imgSrc = ref('')
//图裂地址
const imgerror = ref('')
const vImgerror = {
mounted: (el,binding) =>{
if(el.onerror) {
el.src = binding.value
}
}
}
</script>
3.Vue2.0的全局自定义指令
//在main.js中注册
// 注册一个全局自定义指令 `v-example`
Vue.directive('example', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
el.focus();
}
});
// 在组件中使用
<template>
<input v-example/>
</template>
4.Vue2.0的局部自定义指令
<template>
<div>
<input v-my-directive/>
</div>
</template>
<script>
export default {
directives: {
'my-directive': {
bind(el, binding, vnode) {
// 指令绑定时的操作
},
inserted(el, binding, vnode) {
// 指令绑定到元素后的操作
},
update(el, binding, vnode, oldVnode) {
// 指令所在组件的 VNode 更新时的操作
},
componentUpdated(el, binding, vnode) {
// 指令所在组件的 VNode 及其子 VNode 全部更新后的操作
},
unbind(el, binding, vnode) {
// 指令与元素解绑时的操作
},
}
}
}
</script>
5.Vue3.0自定义指令中的生命周期钩子函数
beforeMount
: 在绑定元素挂载之前调用。mounted
: 绑定元素挂载后调用。beforeUpdate
: 在更新元素之前调用,不包括第一次挂载。updated
: 在更新完成时调用,不包括第一次挂载。beforeUnmount
: 在卸载绑定元素之前调用。unmounted
: 在卸载绑定元素之后调用。
6.Vue2.0自定义指令中的生命周期钩子函数
bind
: 只调用一次,指令第一次绑定到元素时调用。inserted
: 被绑定元素插入父节点时调用。update
: 指令所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。componentUpdated
: 指令所在组件的 VNode 及其子 VNode 全部更新后调用。unbind
: 只调用一次,指令与元素解绑时调用。
7.注意:
局部的自定义指令的优先级要比全局的自定义指令的优先级高。