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.
If you are new to front-end development, you surely have heard about VueJS. It is a progressive JavaScript framework that lets you create exciting web applications! On the other hand, Vuex is a state management tool that enables you to develop your application.
Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.
Both of these could do the work of Vuex, but they aren't enough to replace Vuex completely. Let's take a look at why Vuex is is still necessary, even in Vue 3. First, Vuex offers advanced debugging capabilities that Vue 3 features does not.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With