vue源码阅读疑惑

vue2.1.7版本中,在vue/src/core/instance/init.js文件里出现如下代码:

export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
    const vm: Component = this
    // a uid
    vm._uid = uid++
    // 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)
    callHook(vm, 'beforeCreate')
    initState(vm)
    callHook(vm, 'created')
    initRender(vm)
  }
}

在上述代码中第一、二排中Vue: Class<Component>(options?: Object)写法是什么意思?

阅读 3.3k
5 个回答

vue的源代码引入了一个规范js数据类型的库flow.js(并没有用TS)。

Vue: Class<Component>
// Vue是Component类 类型
options?: Object
// options参数可选,为Object类型

flow的类型检测
js文件的头上有/ @flow / 引用flow

已采纳的回答并不严谨。vue源码确实引入了类型检测flow.js,需要说明的点是:Class<Component>的定义在Class<T>处,具体意思即:
类型Tclass C的一个实例,class C的类型是class<T>的类型(就是说Tclass<T>的一个实例)。
对于源码vue/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)
}
initMixin(Vue)

所以综上:ComponentClass<Component>的一个实例,而Class<Component>的类型即为initMixin(Vue)传入的Vue的类型,简单的说就是Component是function Vue的一个实例。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题