# Vuex 3.x
前言
补充一些官方文档中没有的,但是实际开发中最好需要了解的内容
# 1.安装配置
- 安装依赖
 
npm install vuex
 1
- store/index.js
 
import vuex from 'vuex'
const store = {
  //状态用来存储数据
  state: {
    data: 1,
  },
  //用来获取数据
  getters: {
    count(state) {
      state.data + 1
    },
  },
  //可以放置同步方法
  mutations: {
    setCount(state) {
      state.data + 2
    },
  },
  //可以放置异步方法
  actions: {
    change() {
      setTimeout(() => {
        this.state.data + 3
      }, 1000)
    },
  },
}
export default new vuex.Store(store)
 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
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
- main.js
 
import store from "./store/index"
new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app")
 1
2
3
4
5
6
2
3
4
5
6
- 使用
 
<template>
  <div id="app">
    {{data}}
    <button @click="change">修改状态</button>
  </div>
</template>
<script>
import { mapState, mapGetters,mapMutations, mapActions } from "vuex";
export default {
  name: "app",
  methods: {
    ...mapMutations( ["setCount"]),
    ...mapActions( ["change"]),
    change() {
      this.setCount();
      this.change();
    }
  },
  computed: {
    ...mapState(["data"]),
    ...mapGetters(["count"]),
  }
};
</script>
 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 2.命名空间
modules:可以划分模块存储数据
commit 用于调用mutation,当前模块和其他模块;
dispatch 用于调用action,当前模块和其他模块;
getters 用于获取当前模块getter;
state 用于获取当前模块state;
rootState 用于获取其它模块state;
rootGetters 用于获取其他模块getter;
store/index.js
import vuex from 'vuex'
const store = {
...
}
//可以划分模块存储数据
store.modules={
  namespaced: true,
  user: {
    state: {
      b: 1,
    },
    getters: {
      count(state) {
        state.b + 1
      },
    },
    mutations: {
      change(state) {
        state.b + 2
      },
    },
    actions: {
      change() {
        setTimeout(() => {
          this.state.b + 3
        }, 1000)
      },
    },
  },
}
export default new vuex.Store(store)
 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
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
modules/user.js:user 组件模块文件,里面有独立的 state、getters、mutations、actions
export default {
  namespaced: true,
  state: {
    userName: "我",
  },
  getters: {
    getNewUserName(state) {
      return "是" + state.userName
    },
  },
  mutations: {
    chage_user(state, payload) {
      state.userName = payload
    },
  },
  actions: {
    change_user({ commit }, payload) {
      setTimeout(() => {
        commit("change_user", payload)
        //在action中可以多次触发mutation
      }, 1000)
      setTimeout(() => {
        commit("change_user", "hello")
        //在action中可以多次触发mutation
      }, 2000)
    },
  },
}
 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
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
# 3.工程项目
- vuex 实际使用时一般按下面的方式将各个功能进行拆解
 
index.js
import Vue from "vue"
import vuex from "vuex"
import actions from "./actions"
import mutations from "./mutations"
import state from "./state"
import getters from "./getters"
import user from "./modules/user"
Vue.use(vuex)
export default new vuex.Store({
  modules: {
    user,
  },
  // strict:process.env.NODE_ENV !=='production',
  actions,
  mutations,
  state,
  getters,
})
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
state.js
export default {
  lesson: "vuex学习",
}
 1
2
3
2
3
mutations.js
export default {}
 1
getters.js
export default {
  getNewName(state) {
    return "高级" + state.lesson
  },
}
 1
2
3
4
5
2
3
4
5
actions.js
export default {}
 1
- 使用
 
<template>
  <div id="app">
    {{lesson}}
    {{className}}
    {{u}}
    {{getNewName}}
    {{getNewUserName}}
    <button @click="change">修改状态</button>
  </div>
</template>
<script>
import { mapState, mapGetters, mapActions } from "vuex";
export default {
  name: "app",
  methods: {
    ...mapActions("user", ["change_user"]),
    change() {
      this.$store.state.user.userName = "hello world";
      this["change_user"]("jw");
      this.$store.commit("user/change_user", "jw");
      this.$store.dispatch("user/change_user", "jw");
    }
  },
  computed: {
    ...mapState(["lesson", "className"]),
    ...mapState("user", { u: s => s.userName }),
    ...mapGetters(["getNewName"]),
    ...mapGetters("user", ["getNewUserName"])
  }
};
</script>
 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
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
# 4.持久化插件
npm install vuex-persistedstate --save
 1
- 配置
 
import { createStore } from 'vuex'
// 引入vuex持久化方法createPersistedState
import createPersistedState from 'vuex-persistedstate'
import md from './modules/md
export default createStore({
  state: {},
  mutations: {},
  actions: {},
  getters: {},
  modules: {
    // 模块化数据
    md
  },
  plugins: [
    // veux持久化配置
    createPersistedstate({
      key: 'rabbitstore-client',
      paths: ['md']
    })
  ]
})
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 5.模板
import { getListApi } from "@/apis/list-api";
import { getDataApi } from "@/apis/data-api";
const ENUM = {
    LIST: "list",
    DATA_LIST: "dataList",
};
const HANDLE = {
    GET: "Get",
    SET: "Set",
    REQUEST: "Request",
};
const state = {
    [ENUM.LIST]: [],
    [ENUM.DATA_LIST]: { },
};
const getters = {
    [ENUM.LIST + HANDLE.GET]: (state) => () => {
        return state[ENUM.LIST];
    },
    [ENUM.DATA_LIST + HANDLE.GET]: (state) => () => {
        return state[ENUM.DATA_LIST];
    },
};
const actions = {
    [ENUM.LIST + HANDLE.REQUEST]: async ({ commit, rootState }) => {
        const res = await getListApi({ listId: rootState.listId });
        const {
            result: { code, msg },
            data,
        } = res;
        if (code === 0) {
            commit(ENUM.LIST + HANDLE.SET, data.list);
        } else {
            console.log(msg);
        }
    },
    [ENUM.DATA_LIST + HANDLE.REQUEST]: async ({ commit, state }) => {
        const res = await getDataApi();
        const {
            result: { code, msg },
            data,
        } = res;
        if (code === 0) {
            commit(ENUM.DATA_LIST + HANDLE.SET, data);
        } else {
            console.log(msg);
        }
    },
};
const mutations = {
    [ENUM.LIST + HANDLE.SET]: (state, payload) => {
        state[ENUM.LIST] = payload;
    },
    [ENUM.DATA_LIST + HANDLE.SET]: (state, payload) => {
        state[ENUM.DATA_LIST] = payload;
    },
};
export default {
    namespaced: true,
    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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68