Vue 从入门到进阶之路(十四)
之前的文章我們對 vue 的基礎(chǔ)用法已經(jīng)有了很直觀的認(rèn)識,本章我們來看一下 vue 中的生命周期函數(shù)。
上圖為 Vue官方為我們提供的完整的生命周期函數(shù)的流程圖,下面的案例我們只是走了部分情況流程,但所有的生命周期函數(shù)都涉及到了。
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 的生命周期函數(shù)有:
beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,beforeDestroy,destroyed
這幾個生命周期函數(shù)的意思分別是:
beforeCreate:組件創(chuàng)建前,
created:組件創(chuàng)建完成,
beforeMount:組件掛載前,
mounted:組件掛載完成,
beforeUpdate:組件更新前,
updated:組件更新完成,
beforeDestroy:組件銷毀前,
destroyed:組件成功銷毀。
?
我們通過頁面顯示和控制臺的輸出日志來看一下:
當(dāng)頁面加載時會觸發(fā) beforeCreate,created,beforeMount,mounted 四個生命周期函數(shù)。當(dāng)執(zhí)行到 mounted 生命周期函數(shù)時,數(shù)據(jù)才真正掛在到 DOM 上,所以我們從后臺獲取到的數(shù)據(jù)可以放在 mounted 生命周期函數(shù)中,然后再掛在到 DOM 上。
當(dāng)我們更改數(shù)據(jù)時會觸發(fā)哪些生命周期函數(shù)呢,結(jié)果如下:
當(dāng)我們改變數(shù)據(jù)中的 title 值時,觸發(fā)了 beforeUpdate 和 updated 生命周期函數(shù)。
為了演示 beforeDestroy 和 destroyed 生命周期函數(shù),我們定義了一個子組件,并通過 handleClick() 方法來控制該子組件的掛載和銷毀,當(dāng)我們點擊按鈕使組件銷毀時:
因為我們將 beforeUpdate 和 updated 生命周期函數(shù)定義在了父組件上,所以當(dāng)子組件銷毀時也屬于父組件更新的一種,所以會觸發(fā)這兩個函數(shù)。還觸發(fā)了 beforeDestroy 和 destroyed 生命周期函數(shù),這兩個是在組件銷毀時才觸發(fā)的生命周期函數(shù)。
?
轉(zhuǎn)載于:https://www.cnblogs.com/weijiutao/p/10684448.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的Vue 从入门到进阶之路(十四)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 农业银行信用卡还款日和账单日是几号?怎么
- 下一篇: vue组件间函数调用