• 五、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(() => {
        // 派发并处理完了
    });
    
  • 相关阅读:
    Python 爬虫入门(一)
    Dubbo、Zookeeper集群搭建及Rose使用心得(二)
    Dubbo、Zookeeper集群搭建及Rose使用心得(一)
    JAVA 加密算法初探DES&AES
    Android 蓝牙模块基础操作
    IntelliJ IDEA 使用随笔
    Maven+SSM框架实现简单的增删改查
    记录一次bug解决过程:数据迁移
    SSM框架+Plupload实现断点续传(Spring+SpringMVC+MyBatis+Plupload)
    JAVA开发环境
  • 原文地址:https://www.cnblogs.com/yuxi2018/p/11966806.html
Copyright © 2020-2023  润新知