Vue2源码resolveConstructorOptions函数?

resolveConstructorOptions函数里,会比较superOptionscachedSuperOptions是否相等,通过Vue.extend创建子类构造函数时,Sub.superOptions = Super.options,因此superOptionscachedSuperOptions对象指向同一个内存地址,因此总是会相等的,那为什么还会有if (superOptions !== cachedSuperOptions)这一条件判断呢,或者说,在什么情况下,两者是不相等的呢?

export function resolveConstructorOptions (Ctor: Class<Component>) {

let options = Ctor.options

if (Ctor.super) {

const superOptions = resolveConstructorOptions(Ctor.super)

const cachedSuperOptions = Ctor.superOptions

if (superOptions !== cachedSuperOptions) {

// super option changed,

// need to resolve new options.

Ctor.superOptions = superOptions

// check if there are any late-modified/attached options (#4976)

const modifiedOptions = resolveModifiedOptions(Ctor)

// update base extend options

if (modifiedOptions) {

extend(Ctor.extendOptions, modifiedOptions)

}

options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)

if (options.name) {

options.components[options.name] = Ctor

}

}

}

return options

}

  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.mixin时,会使用mergeOptions更新父组件的options,而mergeOptions会返回一个新的options,这会导致问题中的判断条件成立

以上是 Vue2源码resolveConstructorOptions函数? 的全部内容, 来源链接: utcz.com/p/932820.html

回到顶部