之前的文章我們對 vue 的基礎用法已經有了很直觀的認識,本章我們來看一下 vue 中的生命周期函數。
上圖為 Vue官方為我們提供的完整的生命周期函數的流程圖,下面的案例我們只是走了部分情況流程,但所有的生命周期函數都涉及到了。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>vue</title> 6 <script src="https://cdn.jsdelivr.net/npm/vue"></script> 7 </head> 8 <body> 9 <div id="app"> 10 <child v-if="show"></child> 11 <button @click="handleClick">{{title}}</button> 12 </div> 13 <script> 14 Vue.component("child", { 15 beforeDestroy() { 16 console.log("beforeDestroy", this.$el); 17 }, 18 destroyed() { 19 console.log("destroyed", this.$el); 20 }, 21 template: `<p>我是 child 子組件</p>`, 22 }); 23 var app = new Vue({ 24 el: '#app', 25 data: { 26 title: "hello world", 27 show: true 28 }, 29 beforeCreate() { 30 console.log("beforeCreate", this.$el); 31 }, 32 created() { 33 console.log("created", this.$el); 34 }, 35 beforeMount() { 36 console.log("beforeMounted", this.$el); 37 }, 38 mounted() { 39 console.log("mounted", this.$el); 40 }, 41 beforeUpdate() { 42 console.log("beforeUpdate", this.$el); 43 }, 44 updated() { 45 console.log("updated", this.$el); 46 }, 47 methods: { 48 handleClick() { 49 this.show = !this.show; 50 } 51 } 52 }) 53 </script> 54 </body> 55 </html>
從上面的代碼中我們可以看出 vue 的生命周期函數有:
beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,beforeDestroy,destroyed
這幾個生命周期函數的意思分別是:
beforeCreate:組件創建前,
created:組件創建完成,
beforeMount:組件掛載前,
mounted:組件掛載完成,
beforeUpdate:組件更新前,
updated:組件更新完成,
beforeDestroy:組件銷毀前,
destroyed:組件成功銷毀。
我們通過頁面顯示和控制台的輸出日志來看一下:
當頁面加載時會觸發 beforeCreate,created,beforeMount,mounted 四個生命周期函數。當執行到 mounted 生命周期函數時,數據才真正掛在到 DOM 上,所以我們從后台獲取到的數據可以放在 mounted 生命周期函數中,然后再掛在到 DOM 上。
當我們更改數據時會觸發哪些生命周期函數呢,結果如下:
當我們改變數據中的 title 值時,觸發了 beforeUpdate 和 updated 生命周期函數。
為了演示 beforeDestroy 和 destroyed 生命周期函數,我們定義了一個子組件,並通過 handleClick() 方法來控制該子組件的掛載和銷毀,當我們點擊按鈕使組件銷毀時:
因為我們將 beforeUpdate 和 updated 生命周期函數定義在了父組件上,所以當子組件銷毀時也屬於父組件更新的一種,所以會觸發這兩個函數。還觸發了 beforeDestroy 和 destroyed 生命周期函數,這兩個是在組件銷毀時才觸發的生命周期函數。