vue3 生命周期


vue3 的生命周期與 vue2 是不太相同的,特此整理:

<script setup lang="ts">
import {
  onBeforeMount,
  onBeforeUnmount,
  onBeforeUpdate,
  onUnmounted,
  onUpdated,
  onMounted,
  ref,
  onActivated,
  onDeactivated,
} from "vue";

defineProps<{ msg: string }>();

const count = ref(0);
const name = ref("彭");
let update = () => {
  console.log("update");
  name.value = "點擊了";
};

function table() {
  const gander = "男";
  return {
    gander,
  };
}
let table1 = table();

onBeforeMount(() => {
  console.log("onBeforeMount");
  console.log(name.value);
  console.log(document.getElementById("count"));
});
onMounted(() => {
  console.log("onMounted");
  console.log(name.value);
  console.log(document.getElementById("count"));
});

onActivated(() => {
  console.log("onActivated");
});

onDeactivated(() => {
  console.log("onDeactivated");
});

onBeforeUpdate(() => {
  console.log("onBeforeUpdate");
  console.log(name.value);
});

onUpdated(() => {
  console.log("onUpdated");
  console.log(name.value);
});

onBeforeUnmount(() => {
  console.log("onBeforeUnmount");
});

onUnmounted(() => {
  console.log("onUnmounted");
});
</script>

<template>
  <h1>{{ msg }}</h1>
  <h2 @click="update">{{ name }}</h2>
  <h4 id="count">{{ count }}</h4>
  <h4>{{ table1.gander }}</h4>
</template>

<style scoped>
a {
  color: #42b983;
}

label {
  margin: 0 0.5em;
  font-weight: bold;
}

code {
  background-color: #eee;
  padding: 2px 4px;
  border-radius: 4px;
  color: #304455;
}
</style>

通過 vite 構建的 vue3 項目,ts版本;

onBeforeMount onMounted onBeforUpdate onUpdated onUnMount onUnMounted 

個人認為,在 vue2 中 created 階段進行的接口請求,目前只能放在 vue3 中的 onMounted 階段了

我去看下官方文檔是怎么解釋的。

因為 setup 是圍繞 beforeCreate 和 created 生命周期鈎子運行的,所以不需要顯式地定義它們。換句話說,在這些鈎子中編寫的任何代碼都應該直接在 setup 函數中編寫。

個人理解:只要放在 setup 函數中第一行執行,其實就是 vue2 中的 created 階段!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM