之前總結(jié)了一些vuex的基礎(chǔ)性知識慕匠,只是通過一些簡單的動作來改變 store.js 中的數(shù)據(jù)對象杭朱。這是完全無法滿足工作需求的阅仔,還需要學(xué)習(xí)一些流程判斷。
一弧械、比如說我現(xiàn)在有這么個需求八酒,當(dāng) count < 5 的時候,就停止 count-- 刃唐。這就需要用到 actions
**[actions](https://link.jianshu.com/?t=https%3A%2F%2Fvuex.vuejs.org%2Fzh-cn%2Factions.html)** 定義要執(zhí)行的動作羞迷,如流程的判斷、異步請求
在 store.js 內(nèi)的 actions 中
// 定義 actions 画饥,要執(zhí)行的動作衔瓮,如流程的判斷、異步請求
const actions ={
increment({commit,state}){
commit('increment')
},
decrement({ commit, state }) {
// **通過動作改變的數(shù)據(jù)荒澡,在此處來做判斷是否提交**
if (state.count > 5) {
commit('decrement')
}
}
}
運行項目
4279446-ef01bbfaa66c55f6.gif
二报辱、通過 actions 模擬異步請求
1. 先在 App.vue 中定義好事件
<template>
<div id="app">
<button @click="increment">增加</button>
<button @click="decrement">減少</button>
//異步請求事件
<button @click="incrementAsync">異步增加</button>
<h1>{{count}}</h1>
</div>
</template>
<script>
import {mapGetters,mapActions} from 'vuex'
export default {
name: 'app',
computed:mapGetters([
'count'
]),
methods:mapActions([
'increment',
'decrement',
'incrementAsync'
])
}
</script>
2. 在 store.js 內(nèi)的 actions
中添加 異步 Promise 事件
// 定義 actions ,要執(zhí)行的動作单山,如流程的判斷、異步請求
const actions ={
increment({commit,state}){
commit('increment')
},
decrement({ commit, state }) {
// **通過動作改變的數(shù)據(jù)幅疼,在此處來做判斷是否提交**
if (state.count > 5) {
commit('decrement')
}
},
incrementAsync({commit,state}){
// 模擬異步操作
var a = new Promise((resolve,reject) => {
setTimeout(() => {
resolve();
}, 3000);
})
// 3 秒之后提交一次 increment 米奸,也就是執(zhí)行一次 increment
a.then(() => {
commit('increment')
}).catch(() => {
console.log('異步操作失敗');
})
}
}
1.gif
三、獲取數(shù)據(jù)狀態(tài)
假如我們需要知道數(shù)據(jù)的奇偶數(shù)爽篷,那么就需要在 getters 中來判斷悴晰。
getters 中可以獲取經(jīng)過處理后的數(shù)據(jù),從而來判斷狀態(tài)
在 store.js 的 getters 中加入判斷奇偶數(shù)的方法
var getters={
count(state){
return state.count
},
EvenOrOdd(state){
return state.count%2==0 ? '偶數(shù)' : '奇數(shù)'
}
}
在 App.vue 中加入
<template>
<div id="app">
<button @click="increment">增加</button>
<button @click="decrement">減少</button>
<button @click="incrementAsync">異步增加</button>
<h1>{{count}}</h1>
<!-- 判斷奇偶數(shù)的方法 這種寫法它會自動調(diào)用 EvenOrOdd 方法中的返回值,拿到的是個屬性 -->
<h1>{{EvenOrOdd}}</h1>
</div>
</template>
<script>
import {mapGetters,mapActions} from 'vuex'
export default {
name: 'app',
computed:mapGetters([
// 判斷奇偶數(shù)的方法
'EvenOrOdd',
'count'
]),
methods:mapActions([
'increment',
'decrement',
'incrementAsync'
])
}
</script>
4279446-828bb67e550e3114.gif