# Vuex

# JS 语法

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const state = {
  count: 0,
};

const mutations = {
  increment(state) {
    state.count++;
  },
  decrement(state) {
    state.count--;
  },
};

const actions = {
  increment: ({ commit }) => commit("increment"),
  decrement: ({ commit }) => commit("decrement"),
  incrementIfOdd({ commit, state }) {
    if ((state.count + 1) % 2 === 0) {
      commit("increment");
    }
  },
  incrementAsync({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit("increment");
        resolve();
      }, 1000);
    });
  },
};

const getters = {
  evenOrOdd: (state) => (state.count % 2 === 0 ? "even" : "odd"),
};

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
});
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
35
36
37
38
39
40
41
42
43
44
45
46

# TS 语法


 



 
 
 

 




 


 





 
 
 




 










 









import Vue from "vue";
import Vuex, { ActionContext } from "vuex";

Vue.use(Vuex);

interface State {
  count: number;
}

const state: State = {
  count: 0,
};

const mutations = {
  increment(state: State) {
    state.count++;
  },
  decrement(state: State) {
    state.count--;
  },
};

const actions = {
  increment: ({ commit }: ActionContext<State, any>) => commit("increment"),
  decrement: ({ commit }: ActionContext<State, any>) => commit("decrement"),
  incrementIfOdd({ commit, state }: ActionContext<State, any>) {
    if ((state.count + 1) % 2 === 0) {
      commit("increment");
    }
  },
  incrementAsync({ commit }: ActionContext<State, any>) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit("increment");
        resolve();
      }, 1000);
    });
  },
};

const getters = {
  evenOrOdd: (state: State) => (state.count % 2 === 0 ? "even" : "odd"),
};

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
});
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# 更好的写法