Jordi Sipkens
Jordi Sipkens

Reputation: 595

Vue.JS Vuex store and accessing my api through dependency injection

I'm having difficulties accessing my api within my store modules. I've created an instance of my api, passed it within my vue creation just like the store. However when trying to implement logic in my module, the this.$api does not work like it works in my components. Is there any way to access my already created instance of 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');

So can I access the api instance without creating a new instance in my module or store?

Upvotes: 1

Views: 3167

Answers (1)

Andranik Hovesyan
Andranik Hovesyan

Reputation: 447

I think you should be able to inject api directly to store, like this:

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

Anyways, for Axios, it worked fine: https://forum.vuejs.org/t/accessing-axios-in-vuex-module/29414/3

Upvotes: 8

Related Questions