一、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 的唯一途徑