一、Action 异步操作数据的使用方法
Action 用于处理异步任务, 如果需要通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在 Action 中还是要通过触发Mutation 的方式间接变更数据
(一)定义Action
const myVuex = {
state: {
myState: ''
},
mutations: {
SET_MYSTATE: (state, value) => {
console.log(value, 'mutations同步数据,将获取的最新数据映射到state中---')
state.myState = value
}
},
actions: {
GetWXSSS({ commit }, params) {
console.log('actions--执行查询数据的方法')
return new Promise((resolve, reject) => {
commit('SET_MYSTATE', params || '上班使我快乐。。。')
resolve()
})
}
}
}
(二)触发Action
触发Action的方式有两种:
1、通过dispatch触发store的异步函数,第一个参数为异步函数名(action中定义的函数),第二个参数为携带的参数
this.$store.dispatch('GetWXSSS');
或者
this.$store.dispatch('GetWXSSS', '上班了。。。');
2、通过按需导入 mapActions 函数
在组件中引入mapActions ,在methods中定义,将指定的 actions 函数,映射为当前组件的 methods 函数,在需要存储的地方直接通过调用指定的 actions 函数进行更新
<script>
import { mapActions } from 'vuex'
mounted() {
this.GetWXSSS('使用mapActions')
},
methods: {
...mapActions(['GetWXSSS'])
}
</script>
3、如何获取Action数据?
<script>
import { mapGetters} from 'vuex'
computed: {
...mapGetters(['myState']),
getMyState() {
return this.myState
}
}
</script>
二、Mutation
store 数据改变的唯一方法就是提交 mutations,是修改store 的唯一途径。
1、定义:
处理数据逻辑方法全部放在 mutations,集中监控所有数据的变化
const myVuex = {
state: {
myState: 1
},
mutations: {
SET_MYSTATE: (state, value) => {
console.log(value, 'mutations同步数据,将获取的最新数据映射到state中---')
state.myState += value
}
}
}
2、触发使用
<template>
<div>
<button @click="add($store.state.myVuex.myState)">累加器</button>
<div>结果={{ $store.state.myVuex.myState }}</div>
</div>
</template>
<script>
export default {
name: "VuexComponent",
methods:{
add(addNum){
this.$store.commit('SET_MYSTATE', addNum)
}
}
}
</script>
3、数据获取
this.$store.state.myVuex.myState
三、Action 和 Mutation 的异同点
Mutation:必须同步执行
Action :可以异步,但不能直接操作State
两者进行存储数据都必须经过Mutation,Mutation是修改store 的唯一途径