10

Vuex complains that a new instance of the store cannot be created without calling Vue.use(Vuex). While this is okay generally, I am fiddling with the idea of writing a backend/frontend using the same store. Anybody know the answer?

Thanks.

1 Answer 1

29

TL;DR you can perfectly use Vuex in node (without a browser), even for unit testing. Internally, though, Vuex still uses some code from Vue.

You can't use Vuex without Vue. Because:

That being said, you do require Vue, but you don't require a Vue instance. You don't even require the browser.

So yes, it is pretty usable in the server-side, standalone.

For instance, you could run it using Node.js as follows:

  • Create a sample project:

    npm init -y
    
  • Install the dependencies (note: axios is not necessary, we are adding it just for this demo):

    npm install --save vue vuex axios
    
  • Create a script (index.js):

    const axios = require('axios');
    const Vue = require('vue');
    const Vuex = require('vuex');
    Vue.use(Vuex);
    
    const store = new Vuex.Store({
      strict: true,
      state: {name: "John"},
      mutations: {
        changeName(state, data) {
            state.name = data
        }
      },
      actions: {
        fetchRandomName({ commit }) {
          let randomId = Math.floor(Math.random() * 12) + 1  ;
          return axios.get("https://reqres.in/api/users/" + randomId).then(response => {
            commit('changeName', response.data.data.first_name)
          })
        }
      },
      getters: {
        getName: state => state.name,
        getTransformedName: (state) => (upperOrLower) => {
          return upperOrLower ? state.name.toUpperCase() : state.name.toLowerCase()
        }
      }
    });
    console.log('via regular getter:', store.getters.getName);
    console.log('via method-style getter:', store.getters.getTransformedName(true));
    
    store.commit('changeName', 'Charles');
    console.log('after commit:', store.getters.getName);
    
    store.dispatch('fetchRandomName').then(() => {
        console.log('after fetch:', store.getters.getName);
    });
    
  • Run it:

    node index.js
    
  • It will output:

    via regular getter: John
    via method-style getter: JOHN
    after commit: Charles
    after fetch: Byron
    
Sign up to request clarification or add additional context in comments.

2 Comments

what was the version of Vue you've demostrated here ? It's not working, I get an error: TypeError: Vue.use is not a function. I believe it wasn't made for Vue3, right ?
to make it work just do npm install [email protected] [email protected]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.