Blog>
Snippets

Vuex State Management with TypeScript

Show how to integrate TypeScript with Vuex for type-safe state management in a Vue 3 context.
import { createStore } from 'vuex';

interface State {
  counter: number;
}

// Create the Vuex store with typed state
const store = createStore<State>({ 
  state: { 
    counter: 0
  }, 
  mutations: {
    increment(state) { 
      state.counter++; 
    }
  },
  actions: {
    incrementAsync({ commit }) { 
      setTimeout(() => {
        commit('increment');
      }, 1000);
    }
  }
});

export default store;
This code defines a TypeScript interface for your Vuex state, ensuring that the state will always adhere to the specified structure with typed properties. It then creates a new Vuex store with this state interface, adding a single `counter` property to the state. The store also includes a mutation to increment the counter and an action to perform this increment asynchronously.
import { createApp } from 'vue';
import { store } from './store'; // The store created in the previous step
import App from './App.vue';

const app = createApp(App);

// Tell Vue to use the store
app.use(store);

app.mount('#app');
This snippet is responsible for initializing a new Vue application and binding the Vuex store to it. It imports the store from where it is defined and tells Vue to use this store with the `app.use` method before mounting the app on a DOM element with the specific selector '#app'.
import { useStore } from 'vuex';

export default {
  setup() {
    const store = useStore<State>();

    function incrementCounter() {
      store.commit('increment');
    }

    function incrementCounterAsync() {
      store.dispatch('incrementAsync');
    }

    return {
      counter: computed(() => store.state.counter),
      incrementCounter,
      incrementCounterAsync
    };
  }
};
In this snippet, a Vue component uses the Vuex store with methods to increment the state's counter both synchronously and asynchronously. It begins by importing the `useStore` function and defining the component's setup function. Inside the setup function, it instantiates the store with the proper state type, defines the methods to mutate the state and dispatch actions, and finally returns the state and methods to the template. Here `computed` is assumed to be globally imported or defined elsewhere in the project.