Vue状态管理vuex中actions的用法

  • store

    // store.js
        import Vue from "vue";
        import Vuex from "vuex";
    
        Vue.use(Vuex);
    
        export default new Vuex.Store({
            state: {
                userInof: {
                    token: "登陆凭证",
                    name: "鲁班七号"
                },
                buff: "带蓝buff的"
            },
            getters: {},
            mutations: {
                COMMIT_CHANGE_BUFF(state, obj) {
                    state.buff = obj.buff;
                }
            },
            actions: {
                ACTIONS_CHANGE_BUFF({ commit }, obj) {
                    setTimeout(() => {
                        //异步执行
                        commit("COMMIT_CHANGE_BUFF", obj);
                    }, 2000);
                }
            },
            modules: {}
        });
    
  • App.vue

    // App.vue
        <template>
            <div id="app">
                <p>{{ buff }} - {{ name }}</p>
                <div>
                    <button @click="ACTIONS_CHANGE_BUFF({ buff: '带小龙buff的' })">
                        使用mapActions辅助函数(数组形式)
                    </button>
                </div>
                <div>
                    <button @click="change({ buff: '带大龙buff的' })">
                        使用mapActions辅助函数(对象形式)
                    </button>
                </div>
                <div>
                    <button @click="dispatch({ buff: '带大龙和小龙buff的' })">
                        使用dispatch派发
                    </button>
                </div>
            </div>
        </template>
    
        <script>
        import { mapState, mapActions } from "vuex";
        export default {
            computed: {
                ...mapState({
                    name: status => status.userInof.name,
                    buff: status => status.buff
                })
            },
            methods: {
                ...mapActions(["ACTIONS_CHANGE_BUFF"]),
                ...mapActions({
                    change: "ACTIONS_CHANGE_BUFF"
                }),
                dispatch(obj) {
                    this.$store.dispatch("ACTIONS_CHANGE_BUFF", obj);
                }
            }
        };
        </script>
    

vuex actions 参考:https://vuex.vuejs.org/zh/guide/actions.html

posted @ 2019-08-26 18:39  氵灬  阅读(1195)  评论(0编辑  收藏  举报