vue的生命週期詳解

 

export default {
  name: 'app',
  components: {
    HelloWorld
  },
  data() {
    return {
      msg: "welcome to your vue app"
    }
  },
  beforeCreate() {
    console.log("beforeCreate",this.$el,this.$data,this.msg);
    this.init();
  },
  created() {
    console.log("created",this.$el,this.$data,this.msg);
    this.init();
  },
  beforeMount() {
    console.log("beforeMount",this.$el,this.$data,this.msg);
  },
  mounted() {
    console.log("mounted",this.$el,this.$data,this.msg);
  },
  beforeUpdate() {
    console.log("beforeUpdate",this.$el,this.$data,this.msg);
  },
  updated() {
    console.log("updated",this.$el,this.$data,this.msg);
  },
  beforeDestroy() {
    console.log("beforeDestroy",this.$el,this.$data,this.msg);
  },
  destroyed() {
    console.log("destroyed",this.$el,this.$data,this.msg);
  },
  methods: {
    init() {
      console.error("i is methods init function")
    }
  },
}

1、beforeCreate 

根據官方的圖就能知道, 是發生在初始化實例之前、數據觀測和事件配置之前調用的

2、created

實例創建完成,初始化數據響應式。實例已完成以下的配置:數據觀測(data observer),屬性和方法的運算, watch/event 事件回調。然而,掛載階段還沒開始,$el 屬性目前不可見。

3、beforeMounted

掛載之前被調用。首先會判斷對象是否有el選項,如果有的話就繼續向下編譯,沒有el選項,就停止編譯,也就是說會停止到當前的生命週期,直到有調用vm.$mount(el),才繼續往下執行。

(1).如果vue實例對象中有template參數選項,則將其作爲模板編譯成render函數。
(2).如果沒有template選項,則將外部HTML作爲模板編譯。
(3).可以看到template中的模板優先級要高於outer HTML的優先級。

4、mounted

el 被新創建的 vm.$el 替換,並掛載到實例上去之後調用該鉤子。

(在mounted之前div中還是通過{{msg}}進行佔位的,因爲此時還有掛在到頁面上,還是JavaScript中的虛擬DOM形式存在的。在mounted之後可以看到div中的內容發生了變化)

5、beforeUpdate  updated

當vue發現data中的數據發生了改變,會觸發對應組件的重新渲染,先後調用beforeUpdateupdated鉤子函數。

6、 beforeDestory destoryed

beforeDestroy鉤子函數在實例銷燬之前調用。在這一步,實例仍然完全可用。
destroyed鉤子函數在Vue 實例銷燬後調用。調用後,Vue 實例指示的所有東西都會解綁定,所有的事件監聽器會被移除,所有的子實例也會被銷燬。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章