zoukankan      html  css  js  c++  java
  • 五、Vuex Action

    Action 异步操作

    通常处理异步操作, 通过 store.dispatch 派发一个 action, 在 action 内部进行提交mutation 变更状态

    • action函数接收一个与store实例具有相同方法和属性的context对象。
    • 可以调用 context.commit 提交 mutation
    • 通过 context.state 和 context.getters 获取 state 和 getters

    定义 Action

    const store = new Vuex.Store({
        state: {
            count: 0
        },
        mutations: {
            increment (state) {
                state.count++;
            }
        },
        actions: {
            increment (content) {
                content.commit('increment')
            }
        }
    });
    

    使用 dispatch 分发 action

    // 普通方式
    this.$store.dispatch('increment');
    
    // 派发并传参 
    this.$store.dispatch('increment', 100);
    
    // 以对象的形式分发
    this.$store.dispatch({
        type: 'increment',
        num: 100
    });
    

    mapAction 辅助函数

    import { mapAction } from 'vuex'
    
    export default {
        methods: {
            // 以数组的形式
            ...mapActions([
                // 将 this.increment() 映射为 this.$store.dispatch('increment')
                'increment',
                // 将 this.incrementBy(num) 映射为 this.$store.dispatch('incrementBy')
                'incrementBy'
            ]),
            ...mapActions({
                // 将 this.add() 映射为 this.$store.dispatch('increment')
                add: 'increment'
            })
        }
    }
    

    组合action

    // 返回 Promise, 方便成功后派发下一个action
    actions: {
        actionA ({ commit }) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    commit('someMutation');
                    resolve();
                }, 1000);
            });
        },
        // 派发另一个action
        actionB ({ dispatch, commit}) {
            return dispatch.('actionA').then(() => {
                commit('someOtherMutation');
            });
        }
    }
    
    // 派发action 可以通过 .then 方法指导执行完成了
    this.$store.dispatch('actionA').then(() => {
        // 派发并处理完了
    });
    
  • 相关阅读:
    mysql安装脚本
    vim常用命令
    CentOS 6.5使用国内网易163的源
    053(七十五)
    053(七十四)
    053(七十三)
    053(七十二)
    053(七十一)
    053(七十)
    053(六十九)
  • 原文地址:https://www.cnblogs.com/yuxi2018/p/11966806.html
Copyright © 2011-2022 走看看