Advanced Vuex State Management application is based on Vue 3, written in typescript ✨🎯

Ömer Çelik
4 min readMay 4, 2021
https://vuex.vuejs.org/

What is Vuex?

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.

When Should I Use It?

If you’ve never built a large-scale SPA and jump right into Vuex, it may feel verbose and daunting. That’s perfectly normal — if your app is simple, you will most likely be fine without Vuex. A simple store pattern may be all you need. But if you are building a medium-to-large-scale SPA, chances are you have run into situations that make you think about how to better handle state outside of your Vue components, and Vuex will be the natural next step for you.

Advance Vuex Application Example

You can import the next generation vuex package by running the code below in your project.

npm install vuex@next --save

Then let’s set up the vuex module structure in the project as in the picture below.

First, let’s start configuring with ‘state.ts’.

// state.tsimport { Post } from '@/types'export interface State {
post?: Post
postList?: Post[]
error: boolean
}

We create the ‘getters.ts’ file to access the states.

// getters.tsimport { GetterTree } from 'vuex'
import { State } from './state'
import { RootState } from '@/store/types'
import { Post } from '@/types'
export const getters: GetterTree<State, RootState> = {
getPost(state): Post | undefined {
const { post } = state
return post
},
getPostList(state): Post[] | undefined {
const { postList } = state
return postList
}
}

Actions are similar to mutations, the differences being that:

  • Instead of mutating the state, actions commit mutations.
  • Actions can contain arbitrary asynchronous operations.

Now let’s create the ‘actions.ts’ file.

// actions.tsimport { ActionTree } from 'vuex'
import { State } from './state'
import { RootState } from '@/store/types'
import { Post } from '@/types'
import axios from 'axios'
const url = 'https://jsonplaceholder.typicode.com/posts/'export const actions: ActionTree<State, RootState> = {
async getById({ commit }, id: string): Promise<any> {
await axios.get(url + id).then(response => {
const data: Post | Post[] = response && response.data
commit('getById', data)
return Promise.resolve(data)
}).catch(error => {
return Promise.reject(error)
})
},
async getAll({ commit }): Promise<any> {
await axios.get(url).then(response => {
const data: Post | Post[] = response && response.data
commit('getAll', data)
return Promise.resolve(data)
}).catch(error => {
return Promise.reject(error)
})
},
}

For state updates, there is no access directly from actions, so we use mututions, now let’s create ‘mutations.ts’.

// mutations.tsimport { Post } from '@/types'
import { MutationTree } from 'vuex'
import { State } from './state'
export const mutations: MutationTree<State> = {
getById(state, payload: Post) {
state.error = false
state.post = payload
},
getAll(state, payload: Post[]) {
state.error = false
state.postList = payload
},
}

We bring all of them together and make our module ready.

// index.tsimport { Module } from 'vuex'
import { getters } from './getters'
import { actions } from './actions'
import { mutations } from './mutations'
import { State } from './state'
import { RootState } from '@/store/types'
export const state: State = {
post: undefined,
postList: undefined,
error: false
}
const namespaced = trueexport const post: Module<State, RootState> = {
namespaced,
state,
getters,
actions,
mutations
}

Now we can use our module in our main index.ts file.

import Vuex, { StoreOptions } from 'vuex'
import { RootState } from './types'
import { post } from './modules/post'
const store: StoreOptions<RootState> = {
state: {
version: '1.0.0' // a simple property
},
modules: {
post,
}
}
export default new Vuex.Store<RootState>(store)

Finally, let’s show the use of the store module in the component.

// PostList.vue<template>
<post-card v-for="(post, i) in postList" :key="i" :post="post" />
</template>
<script lang="ts">
import { defineComponent, computed } from "vue";
import { useStore } from "vuex";
import PostCard from "./PostCard.vue";
export default defineComponent({
components: {
PostCard,
},
setup() {
// data
const store = useStore();
// computed
const postList = computed(() => store.state.post.postList);
// created
store.dispatch("post/getAll");
return {
postList,
};
},
});
</script>

You can access the working finalized source code of our sample, which we have examined in detail, from the link below.

The subject of vuex state management, which I have examined in detail, is vital for medium and large scale projects, I hope it has been a useful article, thank you 👋.

--

--