官方文档
官方声明周期图示
具体变化
1. 与 2.x 版本生命周期相对应的组合式 API
-
-> 使用beforeCreate
setup()
-
-> 使用created
setup()
-
beforeMount
->onBeforeMount
-
mounted
->onMounted
-
beforeUpdate
->onBeforeUpdate
-
updated
->onUpdated
-
beforeDestroy
->onBeforeUnmount
-
destroyed
->onUnmounted
-
errorCaptured
->onErrorCaptured
可以发现:
-
beforeCreate
和created
与setup
几乎是同时进行的,所以可以把写在beforeCreate
和created
这两周期的代码直接写在setup
里即可。 - 命名都形如
onXXX
。 -
beforeDestroy
和destroyed
改为onBeforeUnmount
和onUnmounted
,更语义化了。
代码演示:
<template>
<div id="app">
<h1>{{ greet }}</h1>
<button @click="change">vue3</button>
</div>
</template>
<script lang="ts">
import {
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onMounted,
onUpdated,
ref
} from "vue";
export default {
name: "App",
setup() {
const greet = ref("Hello World");
function change() {
greet.value = "Hello Vue3";
}
console.log("setup");
console.log("------------------");
onBeforeMount(() => {
// console.log(el, binding, vnode, prevVnode);
console.log("onBeforeMount");
console.log("------------------");
});
onMounted(() => {
console.log("onMounted");
console.log("------------------");
});
onBeforeUpdate(() => {
console.log("onBeforeUpdate");
console.log("------------------");
});
onUpdated(() => {
console.log("onUpdated");
console.log("------------------");
});
onBeforeUnmount(() => {
console.log("onUpdated");
console.log("------------------");
});
onMounted(() => {
console.log("onMounted");
console.log("------------------");
});
return {
greet,
change
};
}
};
</script>
新增的钩子函数
除了和 2.x 生命周期等效项之外,组合式 API 还提供了以下调试钩子函数:
onRenderTracked
onRenderTriggered
两个钩子函数都接收一个 DebuggerEvent
,与 watchEffect
参数选项中的 onTrack
和 onTrigger
类似:
<template>
<div id="app">
<h1>{{ greet }}</h1>
<button @click="change">vue3</button>
</div>
</template>
<script lang="ts">
import { DebuggerEvent, onRenderTriggered, ref } from "vue";
export default {
name: "App",
setup() {
const greet = ref("Hello World");
function change() {
greet.value = "Hello Vue3";
}
console.log("setup");
console.log("------------------");
onRenderTriggered((event: DebuggerEvent) => {
console.log(event);
console.log("onRenderTriggered");
console.log("------------------");
});
return {
greet,
change
};
}
};
</script>