在Action
中还是要通过触发Mutation
的方式间接变更数据。
在actions
中定义的方法,都会有默认值context
。
context
是和store
对象具有相同方法和属性的对象- 可以通过
context
进行commit
相关操作,可以获取context.state
数据
vuex中定义异步函数(不传参)
vuex中定义actions
mutations: {
add(state){
state.count++
},
addN(state,payload){
this.state.count+=payload.number
}
},
actions: {
addAsync(context){
setTimeout(() => {
context.commit('add')
},5000)
}
}
组件中使用
方式1:组件中在methods
中调用
<button @click="add">点击添加1</button>
add() {
this.$store.dispatch('addAsync')
}
方式2:在组件中,导入mapActions
函数
通过刚才导入的mapActions
函数,将需要的actions
函数映射为当前组件的methods
方法
import {mapActions} from 'vuex'
...mapActions(['addAsync'])
addCount() {//一种写法
this.addAsync()
}
//另一种写法
<button @click="addAsync">点击</button>
vuex中定义异步函数(传参)
vuex中定义actions
addNAsync(context,payload){
setTimeout(() => {
context.commit('addN',payload)
},3000)
}
vue组件中调用
//方式1
addCountN() {
this.$store.dispatch('addNAsync',{
number:8
})
}
//方式2
addCountN() {
this.addNAsync({number:7})
}
actions与Promise结合使用
loadInfo(context){
return new Promise((resolve) => {
setTimeout(() => {
context.commit('add')
resolve()
},2000)
})
}
组件中调用
add() {
this.$store.dispatch('loadInfo').then((res) => {
console.log(res,'hello')
})
}