我还是不够了解Vue - Vue的实例化

Vue的定义

直入主题,Vue定义在/core/instance/index.js中。

import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'

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

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue

这就是Vue的定义,它其实就是一个构造函数,这里值得一提的是,Vue并没有使用ES6 Class的语法,而是通过扩展Vue构造函数的prototype,充分利用javascript原型的设计实现了模块化,可以看到下面很多mixin都是去扩展Vue的功能, 这样的代码设计非常利于阅读和维护。

下面许多__Mixin(Vue)就不多提了,其实就是给Vue.prototype增加方法,以便于其实例化的对象可以使用这些功能。

这篇文章主要是讲讲Vue的实例化过程。

一切的一切都是从new Vue(options)开始,实际呢就是调用了上面看到的this._init(options)
看看_init的定义:

  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)
    }
  }
  • 定义 vm 为当前的执行上下文,也就是指的是当前new出来的实例或者其子组件。
  • startTag endTag与性能相关,通过window.performance打点测试性能。
 // a flag to avoid this being observed
vm._isVue = true
  • 如描述,所有Vue的实例都被标记为_isVue,它的作用是避免实例被set 或者 del划重点!!!意味着在项目中不能直接使用Vue.set(this, key, value) 或 Vue.del(this, key, value),否则会报错。
  if (options && options._isComponent) {
      initInternalComponent(vm, options)
    } else {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
  • Vue的合并策略是很慢的,当注册一个内部组件的时候不需要做特殊的处理,所以就直接初始化内部组件了,而内部组件的标识就是_isComponent,在创建内部组件的第一步,就会将内部组件的option._isComponent设置为true。看下面代码:
export function createComponentInstanceForVnode (vnode: any, parent: any,): Component {
  const options: InternalComponentOptions = {
    _isComponent: true,
    _parentVnode: vnode,
    parent
  }
  // ...
  return new vnode.componentOptions.Ctor(options)
}

这里顺便提一下,全局注册的组件,是注册到Vue.options.components中的,而子组件的创建过程,将会拿到vm.constructor.options扩展到自己的$options中,这就是全局注册的组件能被任意组件使用的原因。

  • mergeOptions其实在有一篇文章讲initGlobalAPI的时侯已经提到了,Vue.options就是在那时定义的,resolveConstructorOptions如果是在new Vue的情况下,就直接返回了Vue.options,如果有子类扩展,则会再次进行复杂的合并之后返回新的options,最后再将参数和新的options进行合并。
  • initLifecycle 这个方法比较简单,只要是初始化跟生命周期相关的属性。
  • initEvents
export function initEvents (vm: Component) {
  vm._events = Object.create(null)
  vm._hasHookEvent = false
  // init parent attached events
  const listeners = vm.$options._parentListeners
  if (listeners) {
    updateComponentListeners(vm, listeners)
  }
}

export function updateComponentListeners (
  vm: Component,
  listeners: Object,
  oldListeners: ?Object
) {
  target = vm
  updateListeners(listeners, oldListeners || {}, add, remove, createOnceHandler, vm)
  target = undefined
}
// add 方法
function add (event, fn) {
  target.$on(event, fn)
}

拿到父级注册事件,如果有,将连接到子组件中。我们想象一个场景,当你在v-on一个自定义组件的时候,会在子组件内部通过$emit那个事件通知父组件,这个场景会帮助理解父组件事件定义到当前组件的问题。这里的具体过程就是,如果组件内部使用v-on注册了事件,那么将会通过add方法也就是$on将事件装载到vm._events中,然后会在子组件$emit的时候,完成回调。
其中once事件,会在执行了事件后,调用$off去移除注册时间。

  • initRender 这里也是对一些属性的赋值,其中重要的是:
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  // normalization is always applied for the public version, used in
  // user-written render functions.
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)

他们会的作用是会创建vnode,具体的会在讲渲染部分详细说明。

  • callHook(vm, 'beforeCreate') initState callHook(vm, 'created')

callHook(vm, 'beforeCreate')callHook(vm, 'created')不用过多说明,调用了Vue的生命周期函数。
initState里面初始化了propsdata等,这里是Vue很核心的部分,通过数据劫持实现了响应式原理。会在将Vue响应时原理在详细介绍。
其实看到这里已经能明白,为何在beforeCreate的时候不能使用this获取实例的数据,而在created可以获取到,关键就是在beforeCreate的时候还没有initState

  • inject/provide 是实现组件通信的新的一种方式,可以实现父子,子孙等通信方式。

总结

这篇文章主要讲了new Vue的过程,可以看到不同的功能被拆分为不同的函数执行,条理逻辑清晰,主线明确,在初始化的最后,如果有 el 属性,则调用 vm.$mount 方法挂载,挂载目的就是把模板渲染成最终的 DOM

    原文作者:李天毫
    原文地址: https://segmentfault.com/a/1190000020342931
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞