Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。
/**
* 1) 包含多个事件回调函数的对象
* 2) 通过执行:commit()来触发 mutation 的调用, 间接更新 state
* 3) 包含异步代码(定时器,ajax)和逻辑代码
* 4) 谁来触发: 组件中:$store.dispatch('action 名称',data1)
*/
代码实例
store.js
actions: {
// content:理解为上下文
// 商品半价
disCount (content) {
// actions中通过commit()提交mutations中的goodsPriceHalve()函数
content.commit('goodsPriceHalve')
},
// 异步的商品半价
/** 对content进行解构
* disCountAsync ({commit}){
setTimeout(() => {
commit('goodsPriceHalve')
},1000)
} */
disCountAsync ({commit}){
setTimeout(() => {
commit('goodsPriceHalve')
},1000)
},
// 统一修改商品名字
/* acyionChangeName()的第一个参数可以理解成是一个对象,第二个参数为事件传递过来的参数
这个参数也需要传递给mutations中相对应的函数中*/
acyionChangeName(content,payload){
// 载荷形式
content.commit('changeName',payload);
},
acyionChangeNameAsync (content,payload){
setTimeout(() => {
// 对象形式
content.commit('changeName',payload.payload)
},1000)
}
}
这里有同步也有异步,有载荷也有没有载荷。
page7.vue
<template>
<div>
<h2>我是第五个页面</h2>
<div>
<input type="text" placeholder="请输入商品的新名字" v-model="inpValue">
<button @click="disCountPrice()">同步商品价格减半</button>
<button @click="disCountPriceAsync()">异步商品价格减半</button>
</div>
<ul class="ul_list">
<li v-for="item in goodsListHalv">
<p class="name">商品:{{item.name}}</p>
<p class="price">价格:¥{{item.price}}</p>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
inpValue:'',
}
},
computed: {
goodsListHalv(){
return this.$store.state.goodsList;
}
},
methods: {
// 注意这里使用箭头函数可能会报错
// 同步商品价格减半;触发事件提交actions中的disCount()函数
disCountPrice: function(){
this.$store.dispatch('disCount')
},
// 异步商品价格减半
disCountPriceAsync: function(){
this.$store.dispatch('disCountAsync')
},
}
}
</script>
page8.vue
<template>
<div>
<h2>我是第六个页面</h2>
<div>
<input type="text" placeholder="请输入商品的新名字" v-model="inpValue">
<button @click="acyionChangeName()">载荷修改商品的名字(字符串)</button>
<button @click="acyionChangeNameAsync()">载荷修改商品的名字(对象)</button>
</div>
<ul class="ul_list">
<li v-for="item in goodsListHalv" :key="item.id">
<p class="name">商品:{{item.name}}</p>
<p class="price">价格:¥{{item.price}}</p>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
inpValue:'',
}
},
computed: {
goodsListHalv(){
return this.$store.state.goodsList;
}
},
methods: {
// 注意这里使用箭头函数可能会报错
// 同步修改商品的名字;触发事件提交actions中的acyionChangeName()函数
acyionChangeName: function(){
this.$store.dispatch('acyionChangeName',this.inpValue)
},
// 异步修改商品的名字;对象 对象中包含两个属性type事件函数,payload参数
acyionChangeNameAsync: function(){
this.$store.dispatch({
type:'acyionChangeNameAsync',
payload:this.inpValue
})
},
}
}
</script>
乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作。
Actions 支持同样的载荷方式和对象方式进行分发。
效果图
代码执行过程:
上面的Action执行过程是:按钮点击–>执行按钮点击事件方法–>执行$store.dispatch('avtions中的对应的函数名',参数)–>执行actions里面对应的方法–>执行mutations里面对应的方法–>修改state里面对应的数据–>页面渲染。
也可以同mutations一样使用常量代替事件类型(更好的管理了事件的名称,使事件名称一目了然)
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = new Vuex.Store({
state: { ... },
actions: {
// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
someAction({commit}) {
commit(SOME_MUTATION)
}
}
})
Vuex(四)--Vue核心概念mutations(唯一可以更改vuex实例中state数据状态的属性对象)_muzidigbig的博客-CSDN博客
异步修改状态并修改视图
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
obj: {
name: 'muzidigbig'
}
},
actions: {
// 异步修改状态并出发视图
objAddAge(context, payload) {
// context.state.obj.age = payload
context.state.obj.name = "xiaohong";
// 动态添加状态并修改视图
Vue.set(context.state.obj, 'age', payload);
// 动态删除状态并修改视图
Vue.delete(context.state.obj,'name');
}
},
modules: {
}
})
模块中
mounted() {
this.$store.dispatch.objAddAge(this.age);
},
在组件中分发 Action
你在组件中使用 this.$store.dispatch('xxx')
分发 action,或者使用 mapActions
辅助函数将组件的 methods 映射为 store.dispatch
调用(需要先在根节点注入 store
):
注入到methods中
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')`
})
}
}
// 直接this.incrementBy(params)使用
总结:
在Mutation中我们组件调用方法使用的是commit,在Action中组件使用的却是dispatch分发。看过vue1.x文档的,可能对commit和dispatch就有点感觉了,或者你看过socket。
这里主要要明白以下几点:
1.Mutation是同步的,Action是异步的;
2.Mutation是直接变更状态,Action提交的是mutation(action函数中接受一个同store实例一样的对象content);
3.Actions和Mutation 都支持载荷方式和对象方式进行分发。
补充知识:
1.mutations 与Actions的区别
首先action与mutation都可以改变state中数据的状态,但是action可以处理异步函数可以在devtools中追踪数据变化,而mutation只可以处理同步函数,当处理异步函数的时候检测不到数据变化
那么是否有人好奇,为什么mutation进行异步操作的时候,为什么页面发生变化了,但是devtools中为什么检测不到数据的变化,而action为什么就可以呢?
下面我们就来探索一下:
为什么mutation必须是同步函数,actions 可以处理异步函数
mutations:{
someMutation (state) {
api.callAsyncMethod(() => {
state.count++
})
}
}
如果我们在mutation中写了异步,commit在触发mutation事件时,异步的回调函数不知道是什么时候执行的,所以在devtools中难以追踪变化
actions 可以做异步操作,但是并不是直接修改数据,而是通过提交mutations 里面的方法
actions: {
setStoreData ({ commit }) {
mockData().then((res)=>{
commit('storeData',res)
})
}
},
mutations:{
storeData(state,payload){
state.data = state.data.concat(payload)
}
}
在页面中触发actions
methods:{
handleData(){
this.$store.dispatch('setStoreData')
}
}
参考文献:链接