使用TypeScript改造vuex

vue 项目引入TypeScript 后,之前vuex的写法需要修改了。在代码编译阶段,会提示你vuex出现了问题。

按照下面的样例编写,可将vuex 尽快与TypeScript 相融合。

1、目录结构

2、app.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Commit } from 'vuex';

export interface State {
    details: object
}

const state: State = {
    details:{}
}

const mutations = {
    ADD_DETAILS: (state: State,details: object) => {
        state.details = details;
    },
    REMOVE_DETAILS: (state: State) => {
        state.details = {}
    }
}

const actions = {
    addDetails(context: {state: State, commit: Commit }, details: object ){
        context.commit('ADD_DETAILS', details);
    },
    removeDetails(context: {state: State, commit: Commit } ){
        context.commit('REMOVE_DETAILS');
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

3、getters.ts

1
2
3
4
5
const getters = {
    details: (state: any) => state.app.details
}

export default getters

4、index.ts

1
2
3
4
5
6
7
8
9
10
11
12
import Vue from "vue";
import Vuex from "vuex";
import app from './modules/app'
import getters from './getters'
Vue.use(Vuex);

export default new Vuex.Store({
  getters,
  modules: {
    app
  }
});