Vue.js store test

John Doe ·

464 Views

1. src/store/index.ts

import { createStore } from 'vuex'

import testModule, {InitialState as InitialStateTestModule} from "@/store/testModule";
...

export default createStore<InitialState>({
  modules: {
    testModule,
    ...
  }
})

export interface InitialState{
   testModule: InitialStateTestModule,
   ...
}

 

2. src/store/testModule.ts

import {Module} from "vuex";
import {InitialState as InitialStateRoot} from "@/store/index";

export interface InitialState{
    count: number
}

const module: Module<InitialState, InitialStateRoot> = {
    namespaced: true,
    state: () => ({
        count: 0
    }),

    /*
     * asynchronous
     */
    actions: {
        increment({commit, dispatch}){
            setTimeout(() => {
                commit("increment");
            }, 1000)
        },
        waitSec(_, sec) {
          return new Promise(resolve => setTimeout(resolve, sec*3000))
        },
        async loadTestBoard({dispatch}) {
          await dispatch('waitSec', 3)
            return `
            <div>TEST</div>
            `
        }
    },

    /*
     * synchronous
     */
    mutations: {
        increment(state){
            state.count = state.count +1
        },
    },

    /*
     * use getters for cache
     */
    getters: {
        xCount (state) {
            return state.count
        }
    }
}

export default module;

 

Vue.js