在使用vue開發過程當中常常會接觸到生命週期的問題,但對於每一個鉤子函數都作了什麼,應用場景比較模糊,但願經過此次梳理讓本身清楚一些。初次寫文章,有不對的地方還望各位多多指正!vue
1. vue實例化過程
從vue實例化開始分析,咱們經過new Vue來實例化來查看一下源碼 在 src/core/instance/init.js 中定義 使用vscode的小夥伴推薦使用Search node_modules插件查找node_modules中的插件方便多了,媽媽不再用擔憂我迷路了node
Vue.prototype._init = function (options?: Object) { initLifecycle(vm) initEvents(vm) initRender(vm) callHook(vm, 'beforeCreate') initInjections(vm) // resolve injections before data/props initState(vm) initProvide(vm) // resolve provide after data/props callHook(vm, 'created') if (process.env.NODE_ENV !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false) mark(endTag) measure(`vue ${vm._name} init`, startTag, endTag) } if (vm.$options.el) { vm.$mount(vm.$options.el) } }
Vue 初始化主要就幹了幾件事情,合併配置,初始化生命週期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等等,vue 把不一樣的功能邏輯拆成一些單獨的函數執行。web
咱們關注到,在這個過程當中插入鉤子函數,提供給開發者調用的機會。在初始化的最後,檢測到若是有 el 屬性,則調用 vm.$mount 方法掛載 vm,掛載的目標就是把模板渲染成最終的 DOM。ajax
2.生命週期鉤子
- 生命週期鉤子自動綁定this到實例上,所以你能夠經過this.操做訪問到數據和方法。注意不能使用箭頭函數例以下方代碼,由於箭頭函數綁定外層的this會一直往上找。
created:()=>{// ...代碼}
複製代碼
- 下面用在各個生命週期中打印下el,data,dom節點
export default { name: 'App', data() { return { title: '標題' } }, methods: { onDestoryClick() { this.$destroy() } }, beforeCreate() { console.log( `\n\nbeforeCreate打頭\n$el :${this.$el}\n$data :${JSON.stringify( this.$data )}\n$refs.head :${JSON.stringify( this.$refs.head )}\nbeforeCreate結尾\n\n` ) console.log(this.$vnode) }, created() { console.log( `\n\ncreated打頭\n$el :${this.$el}\n$data :${JSON.stringify( this.$data )}\n$refs.head :${JSON.stringify(this.$refs.head)}\ncreated結尾\n\n` ) console.log(this.$vnode) }, beforeMount() { console.log( `\n\nbeforeMount打頭\n$el :${this.$el}\n$data :${JSON.stringify( this.$data )}\n$refs.head :${JSON.stringify(this.$refs.head)}\nbeforeMount結尾\n\n` ) console.log(this.$vnode) }, mounted() { console.log( `\n\nmounted打頭\n$el :${this.$el}\n$data :${JSON.stringify( this.$data )}\n$refs.head :${JSON.stringify(this.$refs.head)}\nmounted結尾\n\n` ) console.log(this.$vnode) } }