【vue深入學習第1章】探索 Vue 2 的生命週期:從建立到銷燬

自足發表於2024-07-15

Vue.js 是一個漸進式的 JavaScript 框架,用於構建使用者介面。理解 Vue 的生命週期是掌握這個框架的關鍵之一。在這篇部落格中,我們將深入探討 Vue 2 的生命週期,並透過程式碼示例來展示每個生命週期鉤子的作用。

Vue 例項的生命週期

Vue 例項的生命週期可以分為四個主要階段:

  1. 建立階段:初始化事件和生命週期鉤子。
  2. 掛載階段:將模板編譯成 DOM 並掛載到例項上。
  3. 更新階段:當響應式資料變化時,重新渲染 DOM。
  4. 銷燬階段:清理例項,解綁事件和 DOM。

生命週期鉤子

Vue 提供了一系列的生命週期鉤子函式,讓我們可以在例項的不同階段執行程式碼。以下是 Vue 2 的生命週期鉤子:

  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. activated
  8. deactivated
  9. beforeDestroy
  10. destroyed

程式碼示例

我們透過一個簡單的 Vue 例項來演示這些生命週期鉤子的使用。

<!DOCTYPE html>
<html>
<head>
<title>Vue 2 Lifecycle Example</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">
<p>{{ message }}</p>
<button @click="updateMessage">Update Message</button>
</div>

<script>
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
beforeCreate() {
console.log('beforeCreate: 例項初始化之前');
},
created() {
console.log('created: 例項已經建立');
},
beforeMount() {
console.log('beforeMount: 模板編譯之前');
},
mounted() {
console.log('mounted: 模板已經掛載');
},
beforeUpdate() {
console.log('beforeUpdate: 資料更新之前');
},
updated() {
console.log('updated: 資料更新之後');
},
beforeDestroy() {
console.log('beforeDestroy: 例項銷燬之前');
},
destroyed() {
console.log('destroyed: 例項已經銷燬');
},
methods: {
updateMessage() {
this.message = 'Message Updated!';
}
}
});
</script>
</body>
</html>

解釋

  1. beforeCreate:在 Vue 例項初始化之前呼叫,此時資料和事件都還沒有被初始化。
  2. created:在例項建立完成後呼叫,此時資料和事件都已經被初始化,但模板還沒有編譯。
  3. beforeMount:在掛載開始之前呼叫,相關的 render 函式首次被呼叫。
  4. mounted:在掛載完成後呼叫,此時 DOM 已經被渲染。
  5. beforeUpdate:在資料更新之前呼叫,發生在虛擬 DOM 重新渲染和打補丁之前。
  6. updated:在由於資料更改導致的虛擬 DOM 重新渲染和打補丁之後呼叫。
  7. beforeDestroy:在例項銷燬之前呼叫,此時例項仍然完全可用。
  8. destroyed:在例項銷燬之後呼叫。呼叫後,Vue 例項指示的所有東西都會解綁,所有的事件監聽器會被移除,所有的子例項也會被銷燬。

總結

理解 Vue 的生命週期鉤子可以幫助我們在適當的時間點執行程式碼,從而更好地控制應用的行為。透過這些鉤子,我們可以在例項的建立、更新和銷燬過程中插入自定義邏輯,滿足各種需求。

百萬大學生都在用的AI寫論文工具,篇篇無重複👉: AI寫論文

相關文章