iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 4
1
自我挑戰組

前端新手筆記-Vue.js系列 第 4

Day4 - Vue 生命週期介紹

前言

上一篇文章中,我們已經為大家簡單介紹Vue Instance,並且透過範例讓大家初步了解該如何使用Vue 。而這篇文章我將為大家介紹Vue元件生命週期

透過上篇文章範例,我們可以簡單用模板語法就將資料掛載於畫面上。而我們能這樣輕鬆撰寫,都要歸功於Vue在背後幫我們把建立實體、編譯模板、綁定資料、更新資料等事情透過生命週期(Lifecycle)來處理完成。因此,了解生命週期後,我們就能在不同Vue Instance階段執行不同任務。

Vue 元件實體生命週期(Instance Lifecycle Hooks)

Vue.js 提供實體生命週期鉤子 (紅色框框部分就是hook),讓我們在 instance 不同時期做一些事情。示意圖如下 完整版請參考官網

Vue生命週期hooks 說明:


圖片來源:五倍紅寶石Vue實戰課程

Vue執行順序:


圖片來源:五倍紅寶石Vue實戰課程


Lifecycle hook functions 使用說明

範例
Step1.這邊請大家先打開範例後,記得把console也打開,這樣才能觀察hooks變化喔!
Step2.請把想觀察的生命週期狀態打開。如:你想觀察beforeCreate階段,你就可以把其他狀態先註解
結果如下:

var vm = new Vue({
    el: '#app',
    data: {
      count: 0,
    },
    methods: {
      updateEvent: function () {
        this.count += 1;
      },
    },
    beforeCreate: function () {
      // 元件實體剛被建立,屬性計算之前。(取不到實體中的data)
      console.log('beforeCreate - this.count: ', this.count);
      console.log('beforeCreate - this.$el: ', this.$el);  //$el指的html中的dom
    },
    created: function () {
      // 元件實體已建立,屬性已綁定,但 DOM 還沒生成。
      console.log('created - this.count: ', this.count);  //可以取得實體資料
      console.log('created - this.$el: ', this.$el);
    },
    beforeMount: function () {
      // 模板 (template) 編譯或掛載至 HTML 之前
      console.log('beforeMount - this.$el: ', this.$el);
    },
    mounted: function () {
      // 模板 (template) 編譯或掛載至 HTML 之後
      console.log('mounted - this.$el: ', this.$el);
    },
    beforeUpdate: function () {
      // 元件被更新之前
      console.log('beforeUpdate: ', 
      this.$el.querySelector('h1').innerText, //這邊就是取得html 的h1
      this.count);
    },
    updated: function () {
      // 元件被更新之後
      console.log('updated: ', 
      this.$el.querySelector('h1').innerText, 
      this.count);
    },
    beforeDestroy: function () {
      // 移除 vue instance 之前
      console.log('beforeDestroy');
    },
    destroyed: function () {
      // 移除 vue instance 之後
      console.log('destroyed');
    },
  });

  document.getElementById('del').addEventListener('click', function () {
    vm.$destroy(); //vm指的是new Instance(vue實體)
  });

補充:

Q:如果要透過 ajax / fetch 取得 API 回傳資料交給 Vue.js 處 理理時,應該在哪個階段執⾏?
A:created階段之後都ok(包括created、beforeMount 與 mounted),因為元件實體已經被建立,我們可以取得data資料。老師建議放created階段,不建議在放在mounted 因為資料若為空陣列網頁畫面可能會有一段空白,但可以用loading圖蓋過.

補充:activated、deactivate介紹

activated、deactivated必須搭配keep-alive使用才會跳出來下面alert

activated () {
    alert(`activated! ${this.text}`);
  },
  deactivated () {
    alert(`deactivated! ${this.text}`);
  },

參考資料:
Summer-Vue Instance介紹
Vue.js 17 - 生命週期(Lifecycle)


上一篇
Day3 Vue Instance(實體)介紹
下一篇
Day5 Vue模板語法、V-text、V-html、V-once介紹、Vue指令概述
系列文
前端新手筆記-Vue.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言