Vue.JS Vuex 存储和通过依赖注入访问我的 api

Jor*_*ens 1 vue.js vuex vuex-modules

我在我的商店模块中访问我的 api 时遇到了困难。我已经创建了我的 api 实例,就像商店一样在我的 vue 创建中传递它。但是,当尝试在我的模块中实现逻辑时, this.$api 无法像在我的组件中那样工作。有什么方法可以访问我已经创建的 api 实例吗?

const api = new Api();


/* eslint-disable no-new */
new Vue({
    components: {App},
    router,
    api,               // <--- I want this.
    store,             // <--- To be accesable in the modules of this
    template: '<App/>'
}).$mount('#app');
Run Code Online (Sandbox Code Playgroud)

那么我可以访问 api 实例而不在我的模块或商店中创建新实例吗?

And*_*yan 6

我认为您应该能够直接注入 api 来存储,如下所示:

const store = new Vuex.Store();
const $axios = axios.create();
store.$axios = $axios;
new Vue({
  components: {App},
  router,
  store,
  template: '<App/>'
}).$mount('#app');
Run Code Online (Sandbox Code Playgroud)

无论如何,对于 Axios,它运行良好:https : //forum.vuejs.org/t/accessing-axios-in-vuex-module/29414/3