vue、vueRoute鉤子函數的理解

一:先來張對比圖壓壓驚,理理思路


1.beforeCreated鉤子

該階段組件實例剛創建,組件屬性計算之前(可理解爲組件屬性還未初始化,未綁定,未掛載元素el),比如:el,data,methods等,如果你試圖在beforeCreated鉤子中獲取這些屬性值,會得到undefine的結果,但是可以獲取到this對象,因爲此時組件剛被創建好,所以this已經引用了該組件對象。測試代碼及結果如下:

beforeCreate: function () {
      console.log('<---------beforeCreate 鉤子--------->')
      console.log(this)
      console.log('%c%s', 'color:red', 'el     : ' + this.$el)
      console.log('%c%s', 'color:red', 'data   : ' + this.$data)
      console.log('%c%s', 'color:red', 'message: ' + this.message)
      console.log('%c%s', 'color:red', 'methods: ' + this.methods)
    }



2.created鉤子

該階段組件實例創建完成,組件屬性綁定完成,但DOM還未生成,el屬性還不存在

created: function () {
      console.log('<---------created 鉤子--------->')
      console.log(this)
      console.log('%c%s', 'color:red', 'el     : ' + this.$el)
      console.log('%c%s', 'color:red', 'data   : ' + this.$data)
      console.log('%c%s', 'color:red', 'message: ' + this.message)
      console.log('%c%s', 'color:red', 'methods: ' + this.methods)
    }




3.beforeMount鉤子

該階段組件實例已經創建完成,但是el還未掛載具體元素


3.mount鉤子

該階段組件實例已經創建完成,但是el已掛載具體元素,此時的el屬性不爲undefine

mounted: function () {
      console.log('<---------beforeMount 鉤子--------->')
      console.log(this)
      console.log('%c%s', 'color:red', 'el     : ' + this.$el)
      console.log('%c%s', 'color:red', 'data   : ' + this.$data)
      console.log('%c%s', 'color:red', 'message: ' + this.message)
      console.log('%c%s', 'color:red', 'methods: ' + this.methods)
    }


剩下的beforeUpdate,updated,beforeDestory,destoryed,這裏不再做解釋


篇二:Vue-Route鉤子


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