iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

Vue.js系列 第 8

Lifecycle

今天要介紹的是Vue生命週期的四個階段,先來看一張官網中Vue的生命週期圖吧!
https://ithelp.ithome.com.tw/upload/images/20210812/20139183ewwAGe946b.png
首先當然是要建立一個vue的實體也就是我們在每個專案中都會看到的new Vue()
接著就是進入Vue的4個階段
第一部分是初始化階段:
當我們把值injection到資料中,會觸發befoeCreate和created兩個hook,在befoeCreate時我們的資料和元素都還沒有被建立,要到了created的階段才有真正完成create的動作,但是create的時候我們的element還是沒有被掛載完成的喔!
第二部分是掛載階段:
這裡是掛載前後的兩個hook,一個是beforeMount它是在要顯示到網頁畫面之前的掛載,也就是在complier之前會走到beforeMount;而另一個是mounted就是真正的掛載到畫面上,所以這個時候我們才能真正的去使用element
第三部分是更新階段:
這是一個會很頻繁觸發的階段,因為我們的資料只要有做變動就會觸發到beforeUpdate和Updated
最後一部分是銷毀階段
beforeDestroy是銷毀前的階段,是最後可以操作裡面資料的階段,當進入destroyed階段就是整個生命週期的結束

進入今天的實作前我們先來看官網上的一段說明

Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()). Since an arrow function doesn’t have a this, this will be treated as any other variable and lexically looked up through parent scopes until found, often resulting in errors such as Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function.

這裡他告訴我們不要使用arrow functions去做生命週期的hook,因為在箭頭函式中是沒有this的,所以他會使用到父層的this

接下來我們使用console.log方法到chrome的console來看一下生命週期的變化吧!
https://ithelp.ithome.com.tw/upload/images/20210912/201391830H6wQeKdhc.jpg
這是剛開啟的畫面,從Console中我們可以看到資料已經掛載在我們的畫面上,也就是走到了我們的mounted階段

接下來在輸入框中輸入名字,每輸入一個字以及按下Enter它就會進入一次更新階段
https://ithelp.ithome.com.tw/upload/images/20210912/20139183D7NunAtlsq.jpg
以上就是我們在畫面上做修改時它會牽動beforeUpdate和updated的hook範例

github


上一篇
Class and Style Bindings
下一篇
JSON介紹
系列文
Vue.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言