Safar Safarli
Safar Safarli

Reputation: 81

Vue and Vuex importing module in separate files

I think i have a rare question. I've separate main.js and store.js file, so in store.js file i've imported Vuex and setup a new vuex store then exported it. After that, i've imported this file in main.js file and set up its requirement (import Vuex again in main.js and Vue.use(Vuex) here). But it doesn't work in this way. I've to write Vue.use(Vuex) inside store.js file, Otherwise it throws this error: Error: [vuex] must call Vue.use(Vuex) before creating a store instance.

main.js file:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

import App from './App.vue'

import {store} from './store/store.js';

new Vue({
  el: '#app',
  store: store,
  render: h => h(App)
})

and store.js file:

import Vuex from "vuex";

export const store = new Vuex.Store({
  state: {
    counter: 0
  }
});

Although i've called import {store} from './store/store.js'; after Vue.use(Vuex), so Vuex instance inside store.js file doesn't get executed before Vue.use(Vuex)

I suspect that problem is webpack based, but i can't be sure.

Upvotes: 2

Views: 1734

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38757

Change store.js to import Vue and use Vuex:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    counter: 0
  }
});

Then remove Vue.use(Vuex) from main.js file:

import Vue from 'vue'

import App from './App.vue' 
import {store} from './store/store.js';

new Vue({
  el: '#app',
  store: store,
  render: h => h(App)
})

It's perfectly okay to have a use statement in store.js. This is in fact how it would be (at least at one point) generated using a tool like @vue/cli if you select the vuex option.

Hopefully that helps!

Upvotes: 1

Related Questions