Vue.extend源代码如下:

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 name = extendOptions.name || Super.options.name
  if (process.env.NODE_ENV !== 'production' && name) {
    validateComponentName(name)
  }

  const Sub = function VueComponent(options) {
    this._init(options)
  }
  Sub.prototype = Object.create(Super.prototype)
  Sub.prototype.constructor = Sub
  Sub.cid = cid++
  Sub.options = mergeOptions(
    Super.options,
    extendOptions
  )
  Sub['super'] = Super

  // For props and computed properties, we define the proxy getters on
  // the Vue instances at extension time, on the extended prototype. This
  // avoids Object.defineProperty calls for each instance created.
  if (Sub.options.props) {
    initProps(Sub)
  }
  if (Sub.options.computed) {
    initComputed(Sub)
  }

  // allow further extension/mixin/plugin usage
  Sub.extend = Super.extend
  Sub.mixin = Super.mixin
  Sub.use = Super.use

  // create asset registers, so extended classes
  // can have their private assets too.
  ASSET_TYPES.forEach(function (type) {
    Sub[type] = Super[type]
  })
  // enable recursive self-lookup
  if (name) {
    Sub.options.components[name] = Sub
  }

  // keep a reference to the super options at extension time.
  // later at instantiation we can check if Super's options have
  // been updated.
  Sub.superOptions = Super.options
  Sub.extendOptions = extendOptions
  Sub.sealedOptions = extend({}, Sub.options)

  // cache constructor
  cachedCtors[SuperId] = Sub
  return Sub
}

该代码定义了Vue.extend方法,该方法用于创建一个子类,继承自Vue,且具有父类的全部特性。该方法接受一个参数,即子类的选项对象。

首先,将传入的选项对象和Vue类的选项对象进行合并,得到子类的选项对象Sub.options。然后,创建一个新的函数Sub,该函数的原型链指向Vue.prototype,并将其构造函数指向自身。接着,将Sub的各个属性和方法继承自Vue,并将Sub的cid设置为自增长值。同时,如果子类的选项对象中存在props和computed属性,则调用initProps和initComputed方法,分别为Sub的原型上定义相应的代理getter。最后,将Sub的extend、mixin和use方法指向Vue的同名方法,为Sub的各个属性和方法定义asset registers,以便子类也能拥有自己的私有资源,并将Sub的superOptions、extendOptions和sealedOptions分别设置为父类的选项对象、子类的选项对象和子类的选项对象的副本。最后,将该子类缓存到父类的缓存对象cachedCtors中,并返回该子类。

vueextend源代码

原文地址: https://www.cveoy.top/t/topic/bm4b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录