Vue2 source code analysis (2)

What happened to New Vue


When we use a Vue, we start with new Vue(), and very few people pay much attention to what’s going on behind the scenes. As we all know, the new keyword in JavaScript stands for instantiating an object, and Vue is actually a class. If we look at the source code, In the SRC/core/instance/index. Js.

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)
}
Copy the code

You can see the Vue only through a new keyword initialization, and then call this. _init method, this method in the SRC/core/instance/init. Js is defined.

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) {
      // Initialize component options
      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) // Initialize the declaration period
    initEvents(vm) // Initialize the event center
    initRender(vm) // Initialize render
    callHook(vm, 'beforeCreate') // Trigger the lifecycle beforCreate
    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)
    }
  }
Copy the code

Vue initialization does a few things: merge configurations, initialize the declaration cycle, initialize the event center, initialize render, initialize Data, props, computed, watcher, and so on

conclusion

Vue initialization logic written very clear, the different function logic into a number of separate functions to execute, so that the main line logic at a glance, such a programming idea is very worthy of reference and learning.