说说 Vuex 的 actions 属性

版权声明:如果喜欢,就点个赞呗 O(∩_∩)O~ https://blog.csdn.net/deniro_li/article/details/89294514

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 效果

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/89294514