说说 Vuex 的 actions 属性

Vuex 的 action 属性内,可以定义异步操作逻辑,以满足某些业务场景要求。在组件内,是通过 $store.dispatch 来触发 action 定义的函数。

我们使用 action,来为计数器异步增 1。

1 Promise 方式

main.js:

const store = new Vuex.Store({
    state: {
        count: 0,
    },
    mutations: {
        increment(state, n = 1) {
            state.count += n;
        }
    },
    actions: {
        asyncInrement(context) {
            return new Promise(resolve => {
                setTimeout(() => {
                    context.commit('increment');
                    resolve();
                }, 1000)
            });
        }
    }
});
复制代码

这里使用了 Promise ,在 1 s 后提交了 mutations 中定义的 increment 递增函数。它是 ES6 语法,有三种状态:

状态说明
Pending进行中
Resolved已完成
Rejected失败

index.vue:

<template>

    <div>
        {{count}}
        <button @click="asyncIncrementByAction">+1</button>
    </div>
</template>

<script>
    export default {
        name: "index.vue",
        computed: {
            count() {
                return this.$store.state.count;
            }
        },
        methods: {
            asyncIncrementByAction() {
                this.$store.dispatch('asyncInrement').then(() => {
                    console.log(this.$store.state.count);
                })
            }
        }
    }
</script>

复制代码

2 Callback 方式

也可以使用普通回调来实现异步方案。

main.js

const store = new Vuex.Store({
...
    actions: {
      ...
        asyncInrement2(context, callback) {
            setTimeout(() => {
                context.commit('increment');
                callback();
            }, 1000);
        }
    }
});
复制代码

index.vue:

<template>
    <div>
        ...
        {{count}}
        <button @click="asyncIncrementByAction2">+1(Callback)</button>
    </div>
</template>

<script>
    export default {
        ...
        methods: {
            ...
            asyncIncrementByAction2() {
                this.$store.dispatch('asyncInrement2',() => {
                    console.log(this.$store.state.count);
                });
            }
        }
    }
</script>

复制代码

3 效果

转载于:https://juejin.im/post/5cb2ac7df265da034c701a2b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值