Vue 源碼閱讀2之從0到beforeCreated

     Hello,大家好。現在咱們正式進入Vue源碼閱讀的主體部分。當網頁中存在Vue文件在瀏覽器中運行的時候,Vue的環境已經存在於瀏覽器中。

    當我們在其他腳本中執行var vm=new Vue(.....)時將會開始了Vue對象的一生。

   (1)執行上述程序的時候將會調用Vue源代碼目錄下的/src/core/instance/index.js的Vue函數。這個函數主要的作用是調用Vue原型鏈上的_init函數以實現Vue對象的初始化過程。

function Vue (options) {
  if (
    process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options)
}

(2)Vue原型鏈上的_init函數由源代碼目錄下的/src/core/instance/init.js的initMixin函數實現,從截取的這一部分代碼我們看到最後調用了beforecreated的鉤子函數,表明進入到了beforecreated過程。

也就是從調用_init函數到beforecreated之間進行了

1.設置vm的值爲this值即Vue對象

2.設置Vue對象的ID號

3.設置對象的_isVue屬性爲真

4.將創建vue的參數與option屬性進行合併。

5.初始化生命週期

6.初始化事件處理

7.初始化渲染器

8.使用callhook函數調用beforeCreated函數

const vm: Component = this
    vm._uid = uid++
    let startTag
    let endTag
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag)
    }
    vm._isVue = true
    if (options && options._isComponent) {
      initInternalComponent(vm, options)
    } else {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    if (process.env.NODE_ENV !== 'production') {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    vm._self = vm
    initLifecycle(vm)
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')

 

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