Vue3 - 關於生命週期
tags: Vue
category: Front-End
description: Vue3 - 關於生命週期
created_at: 2022/07/16 16:00:00
回到 手把手開始寫 Vue3
前言
生命週期有點多,不過就用到在放就好。(常用的我相信都記得住的,像是 onMounted
)
先放一張官方的圖
看的很複雜,其中主要是這樣:
生命週期 | 描述 |
---|---|
onBeforeMount | 元件被掛到 DOM 上之前 |
onMounted | 元件被掛到 DOM 上之後 |
onBeforeUpdate | 有資料變動,畫面更新前 |
onUpdated | 有資料變動且畫面更新後 |
onBeforeUnmount | 元件被移除之前 |
onUnmounted | 元件被移除之後 |
在 Vue3
已經沒有 beforeCreate
與 created
了,都被放到了 setup()
中,所以就沒特別寫到表格中。
直接看範例
src/App.vue
<script setup>
import Child from "./components/Child.vue";
import { ref } from "vue";
const isShow = ref(true);
const switchShow = () => {
isShow.value = !isShow.value;
};
</script>
<template>
<button class="bg-blue-500 text-white px-4 py-2" @click="switchShow">
Switch
</button>
<template v-if="isShow"><Child /></template>
</template>
src/components/Child.vue
<script setup>
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
} from "vue";
const num = ref(0);
onBeforeMount(() => {
console.log("onBeforeMount");
});
onMounted(() => {
console.log("onMounted");
});
onBeforeUpdate(() => {
console.log("onBeforeUpdate");
});
onUpdated(() => {
console.log("onUpdated");
});
onBeforeUnmount(() => {
console.log("onBeforeUnmount");
});
onUnmounted(() => {
console.log("onUnmounted");
});
</script>
<template>
<div>num = {{ num }}</div>
<button class="bg-yellow-500 text-white px-4 py-2" @click="() => num++">
Add
</button>
</template>
可以看到說當你點藍色按鈕時,會重複的 console.log
出下面的訊息(假設你狂戳他)
onBeforeUnmount
onUnmounted
onBeforeMount
onMounted
因為他被重複的在 DOM
中被移除,然後再掛上去,所以重複觸發那四個生命週期。
而如果你去戳黃色按鈕,則會重複輸出下面這兩行
onBeforeUpdate
onUpdated
這是因為他的 num
被改變而被觸發。
一時想不到範例,所以就想到的時候,需要用在自己套上去XD
最後更新時間: 2022年07月16日.