Vue.js 實體的一生: 建立 --> 更新 --> 銷毀

圖取自 A Complete Guide to Vue Lifecycle Hooks – with Vue 3 Updates
生命週期的事件可以拆成兩個 hooks (callback function),事件前 & 事件後!
主要有 4 個主要的事件可以使用 (等同於 8 個 hooks ):
Creation 建立元件Mounting 掛載 DOMUpdates 資料被更新Destruction 元件摧毀
這些在生命週期相關階段的 function (hooks),可以當做 option 在 Vue 實體中使用。
ex:
<script>
export default {
mounted() {
console.log('mounted!')
},
updated() {
console.log('updated!')
}
}
</script>
若使用 Vue 3 可以透過 Composition API,import hooks 到專案中就可以使用。
ex:
<script>
import { onMounted } from 'vue'
// 完整
//import {
// onBeforeMount,
// onMounted,
// onBeforeUpdate,
// onUpdated,
// onBeforeUnmount,
// onUnmounted,
// onActivated,
// onDeactivated,
// onErrorCaptured
//} from "vue";
export default {
setup () {
// 寫在setup()中
onMounted(() => {
console.log('mounted in the composition api!')
})
}
}
</script>
對照表:
| Options API | Composition API (寫在setup()中) |
|---|---|
| beforeCreate | 不需要 |
| created | 不需要 |
| beforeMount | onBeforeMount |
| mounted | onMounted |
| beforeUpdate | onBeforeUpdate |
| updated | onUpdated |
| beforeUnmount | onBeforeUnmount |
| unmounted | onUnmounted |
| errorCaptured | onErrorCaptured |
| renderTracked | onRenderTracked |
| renderTriggered | onRenderTriggered |
| activated | onActivated |
| deactivated | onDeactivated |
A Complete Guide to Vue Lifecycle Hooks – with Vue 3 Updates
每日一句:
還好家目錄回來了