分类目录: html5
vue3的生命周期
Post date:
Author: cyy
标签: vue3
Number of comments: no comments
vue3的生命周期函数,可以按需导入到组件中,且只能在 setup() 函数中使用
vue3生命周期和vue2生命周期对比:
beforeCreate-> 使用setup()created-> 使用 setup()- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeDestroy -> onBeforeUnmount
- destroyed -> onUnmounted
- activated -> onActivated (加入了keep-alive之后生效)
- deactivated -> onDeactivated(加入了keep-alive之后生效)
- errorCaptured -> onErrorCaptured
例:
<template>
<section>
<div>num: {{ num }}</div>
<button @click="addNum">addNum</button>
</section>
</template>
<script>
import { ref, onMounted, onUpdated } from "vue";
export default {
setup() {
const num = ref(1);
const addNum = () => {
num.value++;
};
onMounted(() => {
console.log("mounted");
});
onUpdated(() => {
console.log("updated");
});
return { num, addNum };
},
};
</script>
<style lang="scss">
</style>
新的调试钩子函数
- onRenderTracked
- onRenderTriggered
这两个事件都带有一个DebuggerEvent,它使我们能够知道是什么导致了Vue实例中的重新渲染。
export default {
onRenderTriggered(e) {
debugger
// 检查哪个依赖项导致组件重新呈现
}
}
参考了: