本文介紹了Vuex 提升學(xué)習(xí)教程。如果本篇有看不明白的地方,請(qǐng)移步上一篇:Vuex 入門
上一篇我們講了如何通過(guò)一些簡(jiǎn)單的動(dòng)作來(lái)改變 store.js 中的數(shù)據(jù)對(duì)象,在實(shí)際工作中,這是完全無(wú)法滿足工作需求的,所以這篇我們來(lái)說(shuō)說(shuō)如何做一些簡(jiǎn)單的流程判斷。

自制vuex LOGO
一、比如說(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> <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í)行的動(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> <h1>{{count}}</h1> <!-- 判斷奇偶數(shù)的方法 這種寫法它會(huì)自動(dòng)調(diào)用 EvenOrOdd 方法中的返回值,拿到的是個(gè)屬性 --> <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>
判斷奇偶數(shù).gif
如有不明白之處,還請(qǐng)留言交流,或者直接翻看 API
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注