五、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(() => {
    // 派发并处理完了
});

猜你喜欢

转载自www.cnblogs.com/yuxi2018/p/11966806.html