vue3中指令api和组件保持一致,具体表现在:
- bind → beforeMount
- inserted→mounted
- beforeUpdate: new! 元素自身更新前调用,和组件生命周期钩子很像
- update→removed!和udpated基本相同,因此被移除,使用updated代替
- componentUpdated → updated
- beforeUnmount :new!和组件生命周期钩子相似,元素将要被移除之前调用
- unbind → unmounted
vue 2.0指令使用
<template>
<div>
<h1>自定义指令</h1>
<input type="text" v-autofoucs="true" placeholder="测试自定义指令" />
</div>
</template>
<script>
export default {
data() {
return {};
},
directives: {
autofoucs: {
// 参数:el,binding,vnode,oldVnode
bind() {
console.log("bind");
},
inserted(el, { value }, vnode, oldVnode) {
console.log("inserted", el, vnode, oldVnode);
if (value) {
el.focus();
}
},
update() {
console.log("update");
},
componentUpdated() {
console.log("componentUpdated");
},
unbind() {
console.log("unbind");
},
},
},
};
</script>
vue3.0指令使用
<template>
<h1>自定义指令</h1>
<input type="text" v-autoFocus v-model="text" />
</template>
<script lang='ts'>
import { defineComponent } from "vue";
export default defineComponent({
data() {
return { text: "这是一段文本" };
},
directives: {
autoFocus: {
// 参数:el,binding,vnode,oldVnode
beforeMount() {
console.log("beforeMount");
},
mounted() {
console.log("mounted");
},
beforeUpdate() {
console.log("beforeUpdate");
},
updated() {
console.log("updated");
},
beforeUnmount() {
console.log("beforeUnmount");
},
unmounted() {
console.log("unmounted");
},
},
},
});
</script>
<style scoped>
</style>
网友评论