Centralizing Application State with Vuex 4 in Vue 3
Demonstrate setting up Vuex 4 for global state management in a Vue 3 application, including state, mutations, actions, and getters.
import { createStore } from 'vuex';
// Create a new Vuex store instance
const store = createStore({
state() {
return {
// Define your application's state here
counter: 0,
};
},
mutations: {
// Mutations are used to change the state
increment(state) {
state.counter++;
},
},
actions: {
// Actions are used to commit mutations, can be asynchronous
incrementAction({ commit }) {
commit('increment');
},
},
getters: {
// Getters are like computed properties for the store
doubleCounter: state => state.counter * 2,
},
});
export default store;
Creating a new Vuex 4 store with state, mutations, actions, and getters.
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
// Create a Vue 3 application and use the Vuex store
const app = createApp(App);
app.use(store);
app.mount('#app');
Creating and mounting a Vue 3 application, using the Vuex store created earlier.