Vuex的actions属性的具体使用

2020-06-13 10:35:38易采站长站整理

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

vuex action和mutations的区别

action的功能和mutation是类似的,都是去变更store里的state,不过action和mutation有两点不同: