extends
用法
原理
Vue.extend = function (extendOptions = {}) {
const Super = this // Vue基类构造函数
const name = extendOptions.name || Super.options.name
const Sub = function (options) { // 定义构造函数
this._init(options) // _init继承而来
}
Sub.prototype = Object.create(Super.prototype) // 继承基类Vue初始化定义的原型方法
Sub.prototype.constructor = Sub // 构造函数指向子类
Sub.options = mergeOptions( // 子类合并options
Super.options, // components, directives, filters, _base
extendOptions // 传入的组件对象
)
Sub['super'] = Super // Vue基类
// 将基类的静态方法赋值给子类
Sub.extend = Super.extend
Sub.mixin = Super.mixin
Sub.use = Super.use
ASSET_TYPES.forEach(function (type) { // ['component', 'directive', 'filter']
Sub[type] = Super[type]
})
if (name) { 让组件可以递归调用自己,所以一定要定义name属性
Sub.options.components[name] = Sub // 将子类挂载到自己的components属性下
}
Sub.superOptions = Super.options
Sub.extendOptions = extendOptions
return Sub // 返回子组件的构造函数
}最后更新于