您好,登錄后才能下訂單哦!
這篇文章主要介紹Vuex如何通過(guò)actions模擬異步請(qǐng)求,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
一、比如說(shuō)我現(xiàn)在有這么個(gè)需求,當(dāng) count < 5 的時(shí)候,就停止 count-- 。這就需要用到 actions
actions 定義要執(zhí)行的動(dòng)作,如流程的判斷、異步請(qǐng)求
在 store.js 內(nèi)的 actions 中
// 定義 actions ,要執(zhí)行的動(dòng)作,如流程的判斷、異步請(qǐng)求 const actions ={ increment({commit,state}){ commit('increment') }, decrement({ commit, state }) { // **通過(guò)動(dòng)作改變的數(shù)據(jù),在此處來(lái)做判斷是否提交** if (state.count > 5) { commit('decrement') } } }
運(yùn)行項(xiàng)目
二、通過(guò) actions 模擬異步請(qǐng)求
1. 先在 App.vue 中定義好事件
<template> <div id="app"> <button @click="increment">增加</button> <button @click="decrement">減少</button> //異步請(qǐng)求事件 <button @click="incrementAsync">異步增加</button> <h2>{{count}}</h2> </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í)行的動(dòng)作,如流程的判斷、異步請(qǐng)求 const actions ={ increment({commit,state}){ commit('increment') }, decrement({ commit, state }) { // **通過(guò)動(dòng)作改變的數(shù)據(jù),在此處來(lái)做判斷是否提交** 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('異步操作失敗'); }) } }
運(yùn)行項(xiàng)目
三、獲取數(shù)據(jù)狀態(tài)
假如我們需要知道數(shù)據(jù)的奇偶數(shù),那么就需要在 getters 中來(lái)判斷。
getters 中可以獲取經(jīng)過(guò)處理后的數(shù)據(jù),從而來(lái)判斷狀態(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> <h2>{{count}}</h2> <!-- 判斷奇偶數(shù)的方法 這種寫法它會(huì)自動(dòng)調(diào)用 EvenOrOdd 方法中的返回值,拿到的是個(gè)屬性 --> <h2>{{EvenOrOdd}}</h2> </div> </template> <script> import {mapGetters,mapActions} from 'vuex' export default { name: 'app', computed:mapGetters([ // 判斷奇偶數(shù)的方法 'EvenOrOdd', 'count' ]), methods:mapActions([ 'increment', 'decrement', 'incrementAsync' ]) } </script>
以上是“Vuex如何通過(guò)actions模擬異步請(qǐng)求”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。