vue构造器的初始选项
Vue内部的默认选项
vue
提供选项对象来描述行为,内部会自带内置的默认选项,与用户所定义的选项参与vue
实例初始化中
通过观察源码得知
var ASSET_TYPES = [
'component',
'directive',
'filter'
];
// 原型上创建了一个指向为空对象的options属性
Vue.options = Object.create(null);
ASSET_TYPES.forEach(function (type) {
Vue.options[type + 's'] = Object.create(null);
});
// 这用于标识“基础”构造函数,以在 Weex 的多实例场景中扩展所有普通对象组件。
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue;
Vue内部的默认选项会保留在静态的options
属性上,从源码看Vue
自身有四个默认配置选项,分别是component,directive, filter
以及返回自身构造器的_base
,components
是需要注册的组件选项,directives
是需要注册的指令,而filter
则代表需要注册的过滤器。
深入解析,可以发现Vue
为components
提供了keepAlive,transition,transitionGroup
的内置组件,为directives
提供了v-model,v-show
的内置指令,filter
无默认值
var builtInComponents = {
KeepAlive: KeepAlive
};
var platformDirectives = {
model: directive,
show: show
};
var platformComponents = {
Transition: Transition,
TransitionGroup: TransitionGroup
};
extend(Vue.options.components, builtInComponents);
// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives);
extend(Vue.options.components, platformComponents);
extend
方法实现对象合并:
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
API
方法
在initGlobalAPI
方法中会通过执行initAssetRegisters(vue)
给Vue
原型添加vue.component,vue.directive,vue.filter
函数
function initGlobalAPI (Vue) {
...
initAssetRegisters(Vue);
}
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
ASSET_TYPES.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
if (type === 'component') {
validateComponentName(id);
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id;
definition = this.options._base.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
this.options[type + 's'][id] = definition;
return definition
}
};
});
}
综上,Vue
初始选项 / 资源:
Vue.options = {
components: {
KeepAlive: {}
Transition: {}
TransitionGroup: {}
},
directives: {
model: {inserted: ƒ, componentUpdated: ƒ}
show: {bind: ƒ, update: ƒ, unbind: ƒ}
},
filters: {}
_base
}
参考:
[1].https://cn.vuejs.org/v2/api/#components
[2].
vue^2.6.10
源码[3].https://www.bookstack.cn/read/5865c0921b69e6006b3145a1/spilt.2.src-%E4%B8%B0%E5%AF%8C%E7%9A%84%E9%80%89%E9%A1%B9%E5%90%88%E5%B9%B6%E7%AD%96%E7%95%A5.md