入口函数
export function initMixin(Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
//...省略代码
//merge options
if (options && options._isComponent) {
initInternalComponent(vm, options)
} else {
//定义$options属性
//vm.constructor 就是Vue函数
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
//...省略代码
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
};
}
mergeOptions 函数
export function mergeOptions (
parent: Object,
child: Object,
vm?: Component
): Object {
if (typeof child === 'function') {
child = child.options
}
//props数据规范化处理
normalizeProps(child, vm)
//inject规范化处理
normalizeInject(child, vm)
//
normalizeDirectives(child)
// Apply extends and mixins on the child options,
// but only if it is a raw options object that isn't
// the result of another mergeOptions call.
// Only merged options has the _base property.
if (!child._base) {
if (child.extends) {
parent = mergeOptions(parent, child.extends, vm)
}
if (child.mixins) {
for (let i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm)
}
}
}
const options = {}
let key
for (key in parent) {
//将parent中key全部注入options中
mergeField(key)
}
for (key in child) {
//将child中存在,但在parent中不不存在的key注入options中
if (!hasOwn(parent, key)) {
mergeField(key)
}
}
function mergeField (key) {
const strat = strats[key] || defaultStrat
options[key] = strat(parent[key], child[key], vm, key)
}
return options
}
-
parent其实就是父options;
-
child其实就是当前传入的几new Vue({})中传入的options
-
normalizeProps(child, vm)
-
normalizeInject(child, vm)
-
normalizeDirectives(child)
-
执行完for (key in parent) {}之后
-
执行完for (key in child) {}之后
export function resolveConstructorOptions (Ctor: Class<Component>) {
// Ctor为Vue构造函数
let options = Ctor.options
if (Ctor.super) {
// 存在基类,递归解析基类构造函数的选项
const superOptions = resolveConstructorOptions(Ctor.super)
const cachedSuperOptions = Ctor.superOptions
if (superOptions !== cachedSuperOptions) {
// 说明基类构造函数选项已经发生改变,需要重新设置
Ctor.superOptions = superOptions
// 检查 Ctor.options 上是否有任何后期修改/附加的选项
const modifiedOptions = resolveModifiedOptions(Ctor)
// 如果存在被修改或增加的选项,则合并两个选项
if (modifiedOptions) {
extend(Ctor.extendOptions, modifiedOptions)
}
// 选项合并,将合并结果赋值为 Ctor.options
options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
if (options.name) {
options.components[options.name] = Ctor
}
}
}
return options
}
后续补充