Blog>
Snippets

State Management in Vue.js 3 SPA with Vuex

Setting up a Vuex store to manage the state of a Vue.js 3 single-page application, ensuring reactivity and consistency across components.
import { createStore } from 'vuex';

// Define your state structure
const state = {
  counter: 0,
};

// Define mutations to change state
const mutations = {
  increment(state) {
    state.counter++;
  },
  decrement(state) {
    state.counter--;
  },
};

// Create a Vuex store instance
const store = createStore({
  state,
  mutations,
});

export default store;
This code snippet creates a Vuex store with a simple 'counter' state and 'increment'/'decrement' mutations. The 'createStore' function from 'vuex' initializes the store.
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

// Create the Vue application and use the Vuex store
const app = createApp(App);

app.use(store);

app.mount('#app');
This code snippet sets up the Vue application, imports the Vuex store we previously defined, and then uses this store with the Vue application. Finally, it mounts the app to the DOM element with the id 'app'.
<template>
  <div>
    <p>{{ counter }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';

export default {
  computed: {
    ...mapState(['counter']),
  },
  methods: {
    ...mapMutations(['increment', 'decrement']),
  },
};
</script>
This Vue component template uses two buttons to either increment or decrement the shared 'counter' state. 'mapState' creates computed properties that return the state from the store, and 'mapMutations' maps the store mutations to component methods.