mutations
中所有的代码都是同步代码- 都有的状态的改变都应该在
mutations
中改变
但是遇到异步请求怎么办?
actions
中可以写任何的异步代码- 但是
actions
不能修改状态,最终状态的修改还是在mutations
中修改状态 - 所以定义的action中传递的参数是一个上下文对象,在这个上下文对象中有一个
commit
方法,专门用来提交到mutation
中修改状态
例子
模板
<script>
import { mapState } from 'vuex'
export default {
methods: {
incrementCount(num) {
this.$store.dispatch("incrementAsync", num).then(data => {
console.log(data);
})
}
},
computed: {
...mapState(["count"]),
}
}
</script>
<template>
<p>count:{{ count }}</p>
<button @click="incrementCount(2)">changeCount</button>
</template>
创建store
import { createStore } from "vuex";
// 创建一个新的 store 实例
const store = createStore({
state() {
return {
count: 0
};
},
actions: {
incrementAsync(context, n) {
// context中有commit state getters 等
return new Promise(resolve => {
setTimeout(() => {
context.commit("increment", n)
resolve("执行成功")
}, 1000)
})
}
},
mutations: {
increment(state, n) {
state.count = state.count + n
}
}
});
export default store;
效果
对于代码的解释
- 我们出发的
action
返回什么值,我们就能拿到什么值,比如例子中我们返回的是promise
,所以我们可以调用then
方法 - 触发
action
,除了例子中的方法,还有其他的两种形式
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
- 在
action
的第一个参数是一个对象,对象中有commit
state
getters
等
mapActions
mapActions
是一个语法糖,他可以直接将actions
映射到组件中
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
}