1// store/numStore/index.js
2export default {
3 // 如果命名空间的值为true,那么我们才能把这个目录作为模块去使用
4 namespaced: true,
5 state: {
6 num: 10,
7 },
8 getters: {
9 doubleNum(state) {
10 return state.num * 2;
11 },
12 },
13 mutations: {
14 addNum(state, payload) {
15 state.num += payload;
16 },
17 },
18 actions: {
19 changeNum(context, payload) {
20 setInterval(() => {
21 context.commit("addNum", payload);
22 }, 1000);
23 },
24 },
25};
终极拆分
1import state from "./state";
2import getters from "./getters";
3import mutations from "./mutations";
4import actions from "./actions";
5export default {
6 namespaced: true, // 命名空间
7 state,
8 getters,
9 mutations,
10 actions,
11};
1// store/index.js
2import Vue from "vue";
3import Vuex from "vuex";
4import numStore from "./numStore";
5
6Vue.use(Vuex);
7
8export default new Vuex.Store({
9 modules: {
10 numStore,
11 },
12});
1<template>
2 <div>
3 <p>{{ num }}</p>
4 <p>{{ doubleNum }}</p>
5 <button @click="addNum(10)">同步按钮</button>
6 <button @click="changeNum(20)">异步按钮</button>
7 </div>
8</template>
9
10<script>
11import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
12export default {
13 data() {
14 return {};
15 },
16 computed: {
17 ...mapState({
18 num: (state) => state.numStore.num,
19 }),
20 ...mapGetters({
21 doubleNum: "numStore/doubleNum",
22 }),
23 },
24 methods: {
25 ...mapMutations({
26 addNum: "numStore/addNum",
27 }),
28 ...mapActions({
29 changeNum: "numStore/changeNum",
30 }),
31 },
32};
33</script>