上篇文章有提到在core/index.js中会调用initGlobalAPI来给Vue上挂载全局 api,也就是各种静态函数。这些静态函数是在我们业务代码调用new Vue之前就执行的了。 这里就来记录具体有哪些全局 api。
函数定义为:
1 | export function initGlobalAPI(Vue: GlobalAPI) { |
首先定义Vue.config,之后会在这上面添加各种全局配置。
ASSET_TYPES数组中含有component、directive和filter,所以之后就有了Vue.options .components、Vue.options.directives和Vue.options.filter3 个空对象。
builtInComponents中只含有一个KeepAlive组件,所以经过
1 | extend(Vue.options.components, builtInComponents); |
就有了第一个全局组件<keep-alive>.
initUse
定义了Vue.use,此函数就是用来安装各种 Vue 插件的。
1 | Vue.use = function(plugin: Function | Object) { |
可以看到插件安装的代码非常简洁,然后Vue.installedPlugins会存放所有已安装过的插件。
initMixin
定义了Vue.mixin方法:
1 | Vue.mixin = function(mixin: Object) { |
经过mergeOptions的处理,mixin 的选项就会和Vue.options混合到一起了,效果是全局性的。
mergeOptions涉及到各种合并策略,在另一篇博客vue-i18n中有详细的介绍,这里就不再重复。
initExtend
定义了Vue.extend方法,Vue.extend会返回一个VueComponent构造函数,它会继承Vue函数。
1 | Vue.cid = 0; |
大部分代码都很简单,就是典型的 js 继承,然后设置了一堆变量各种引用。 其中的initProps和initComputed单独说下。
initProps
用于初始化Comp.prototype的props。在Sub.prototype._props对象中存储每一个Sub.options.props上每一个prop,以便在Sub.prototype进行代理访问.
1 | function initProps(Comp) { |
这样之后,访问Comp.prototype[key]会实际访问Comp.prototype._props[key],而vm._props会在src/core/instance/state.js的initState中得到初始化,vm._props[key]指向一个组件的具体prop。
initComputed
用于初始化Comp.prototype的响应式computed
1 | function initComputed(Comp) { |
initAssetRegisters
用于定义Vue.component、Vue.directive和Vue.filter,它们都是定义全局的 options 的,成功后会把结果放到Vue.options.xxxx上。
1 | // ASSET_TYPES => [component, directive, filter] |
至此,所有的 Vue 静态函数就全局介绍完了~~~ 最终我们得到的全局 api 有
Vue.configVue.util.warn/extend/mergeOptions/defineReactiveVue.setVue.deleteVue.nextTickVue.options,内部包含components、directives、filters、_baseVue.useVue.mixinVue.extendVue.componentVue.directiveVue.filter