Vue源码小问答一:为什么option.data的类型必须是function

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/billll/article/details/79111350

在调用Vue.extend( options )进行Vue实例初始化时,option.data的类型必须是function,否则对导致该方法构造出的实例共享同一data对象。

具体原因分析如下:

Vue.extend方法本身的返回值是一个构造函数,通过new调用返回的构造方法我们就可以得到一个vue实例对象。这个构造函数会调用core模块中的_init函数已完成对象的初始化工作。

_init(option)方法会读取option.data

如果option.data是function类型,则执行这个方法得到data对象。如果不是方法类型,则直接使用这个对象作为data。

所以使用extend方法时,option.data必须为function

Vue.extend = function (extendOptions: Object): Function {
    extendOptions = extendOptions || {}
    // this在这里指向Vue方法
    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

    // 返回的vue实例构造方法
    const Sub = function VueComponent (options) {
      this._init(options)
    }
    // Super就是Vue方法,Super.prototype上有_init方法
    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
  }
}

猜你喜欢

转载自blog.csdn.net/billll/article/details/79111350