Vue规定:在调用Vue.use()方法使用插件时,如果插件是一个对象,那么这个对象需要暴露一个install方法;如果插件是一个函数,那么这个函数会被视为install方法
Vue.use()源码(在Vue3源码搜索createAppAPI
即可查看use方法源码):
use(plugin, ...options) {
if (installedPlugins.has(plugin)) {
warn$1(`Plugin has already been applied to target app.`);
}
else if (plugin && isFunction(plugin.install)) {
installedPlugins.add(plugin);
plugin.install(app, ...options);
}
else if (isFunction(plugin)) {
installedPlugins.add(plugin);
plugin(app, ...options);
}
else {
warn$1(`A plugin must either be a function or an object with an "install" ` +
`function.`);
}
return app;
}
可以看到use调用了插件的install方法,并将app传递给了该方法。接下来是Vuex的install方法源码:
Store.prototype.install = function install (app, injectKey) {
app.provide(injectKey || storeKey, this);
app.config.globalProperties.$store = this;
var useDevtools = this._devtools !== undefined
? this._devtools
: true ;
if (useDevtools) {
addDevtools(app, this);
}
};
可以看到install方法将Vuex挂载到了app.config.globalProperties上。最后在mounted中打印this,可以看到:$store
已经和$router
、$route
等平级