Vue3调用Vue.use()方法使用Vuex(源码解析)

Vue规定:在调用Vue.use()方法使用插件时,如果插件是一个对象,那么这个对象需要暴露一个install方法;如果插件是一个函数,那么这个函数会被视为install方法

点击查看Vue.use()官方介绍

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等平级
Vue3调用Vue.use()方法使用Vuex(源码解析)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值