这是我参与8月更文挑战的第2天,活动详情查看: 8月更文挑战
前言
前边在看参数合并的时候,最后提到了mixin。从代码看到全局指令Vue.mixin的内部实现就是直接调用mergeOptions,官方文档在介绍mixin的时候也提了一句,Vue.extend()也使用的跟mixin同样的合并策略。今天就来看下extend的具体实现:
Vue.extend
Vue.extend是一个全局API,定义在src/core/global-api/extend.js
export function initExtend (Vue: GlobalAPI) {
/**
* 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
/**
* Class inheritance
*/
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的‘子类’,接受一个包含组件选项的对象作为参数。接下来就来具体看一下这段代码到底做了什么
SuperId
const Super = this
const SuperId = Super.cid
const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {})
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
从代码可以看出SuperId主要是配合cachedCtors为缓存服务的。这里的this就是extend方法的调用者,也就是Vue。
看一下这个cid:
/**
* 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
从上边注释中可以看出每个实例,包括Vue都有一个唯一的cid来标记自己。所以SuperId是唯一的。
同时这里判断了传入的extendOptions对象有没有_Ctor属性,如果没有则给_Ctor赋值一个空对象。
validateComponentName
接下来处理组件名,如果扩展对象传入了name字段则直接使用,否则从父类Super的options对象获取。
const name = extendOptions.name || Super.options.name
然后判断组件名称是否合法,调用了validateComponetName方法,定义在src/core/util/options.js
export function validateComponentName (name: string) {
if (!new RegExp(`^[a-zA-Z][\-\.0-9_${unicodeRegExp.source}]*$`).test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'should conform to valid custom element name in html5 specification.'
)
}
if (isBuiltInTag(name) || config.isReservedTag(name)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + name
)
}
}
大概就是要求我们的组件名称不能用html已有的标签名等,具体的正则定义在src/core/util/lang.js,这里细节比较多,有兴趣可以去看下这篇介绍配置的文章。
Sub
接下来就是extend函数的重点了,通过原型继承的方式把一个对象转化为一个继承于Vue的构造函数。可以看到每次去实例化Sub的时候,都会去执行_init走一次Vue的初始化逻辑。
const Sub = function VueComponent (options) {
this._init(options)
}
Sub.prototype = Object.create(Super.prototype)
Sub.prototype.constructor = Sub
Sub['super'] = Super
将Sub构造函数唯一标志cid加1,然后调用mergeOptions合并参数。
Sub.cid = cid++
Sub.options = mergeOptions(
Super.options,
extendOptions
)
在合并完参数后,初始化props和computed
if (Sub.options.props) {
initProps(Sub)
}
if (Sub.options.computed) {
initComputed(Sub)
}
将父类的extend,mixin,use,钩子方法复制给子类
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend
Sub.mixin = Super.mixin
Sub.use = Super.use
ASSET_TYPES.forEach(function (type) {
Sub[type] = Super[type]
})
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub
}
保存父类和组件对象自身的options参数,以及最初传入extendOptions对象
// 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)
将Sub对象缓存到_Ctor对象中,并且以父类的cid为key
// cache constructor
cachedCtors[SuperId] = Sub
return Sub