Vue source notes - data driven - what happened to new Vue

Posted by scripterdx on Mon, 25 Nov 2019 15:05:17 +0100

Vue version: 2.5.17-beta.0

When new Vue(options) calls the Vue function in the src/core/instance/index.js file. The source code is as follows:

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)
}

You can see that this. Init (options) method is called after initialization. In fact, this method is in src/core/instance/init.js. The source code is as follows:

Vue.prototype._init = function (options?: Object) {
    const vm: Component = this
    // a uid
    vm._uid = uid++

    let startTag, endTag
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag)
    }

    // a flag to avoid this being observed
    vm._isVue = true
    // merge options
    if (options && options._isComponent) {
      // optimize internal component instantiation
      // since dynamic options merging is pretty slow, and none of the
      // internal component options needs special treatment.
      initInternalComponent(vm, options)
    } else {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    // expose real self
    vm._self = vm
    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')

    /* istanbul ignore if */
    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)
    }
}

The above source code is roughly divided into three steps:

  1. The options passed in when options is new Vue(options) and are merged into vm.$options through the mergeOptions method.
  2. Call initLifecycle(vm), initEvents(vm), initRender(vm), initState(vm) functions to initialize the lifecycle, event center, rendering, data props computed watcher, etc.
  3. Call vm.$mount(vm.$options.el) to mount and render to the real dom.

Topics: Javascript Vue