initExtend方法如何保证cachedCtors.SuperId获取到正确缓存

来源:3-2 createComponent

慕先生4328837

2022-06-09

每次执行initExtend, Vue.cid = 0, 即SuperId = 0, 每个组件optionsextendOptions._Ctor.0 = sub, 都是0指向组件的构造函数。这样的话 为什么不直接用extendOptions._Ctor = sub

export function initExtend (Vue: GlobalAPI) {

  Vue.cid = 0
  let cid = 1
  Vue.extend = function (extendOptions: Object): Function {
    extendOptions = extendOptions || {}
    const Super = this
    const SuperId = Super.cid
    const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {})

    if (cachedCtors[SuperId]) {
      return cachedCtors[SuperId]
    }

    const Sub = function VueComponent (options) {
      this._init(options)
    }

    cachedCtors[SuperId] = Sub
    return Sub
  }
}
写回答

1回答

ustbhuangyi

2022-06-09

/**
   * Each instance constructor, including Vue, has a unique
   * cid. This enables us to create wrapped "child
   * constructors" for prototypal inheritance and cache them.
   */
  Vue.cid = 0
  let cid = 1

其实源码的注释已经给答案了

0
4
k849975
回复
慕先生4328837
我觉得extend只有Vue才有,superid都只会是0,然后是靠const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {})这行代码来识别是否是相同组件的,所以它不需要是++。
2022-06-29
共4条回复

Vue.js 源码深入解析 深入理解Vue实现原理

全方位讲解 Vue.js 源码,进阶高级工程师

4986 学习 · 1038 问题

查看课程