Vuex 提升
上一篇我们讲了如何通过一些简单的动作来改变 store.js 中的数据对象,在实际工作中,这是完全无法满足工作需求的,所以这篇我们来说说如何做一些简单的流程判断。
自制vuex LOGO
一、比如说我现在有这么个需求,当 count < 5 的时候,就停止 count-- 。这就需要用到 actions
actions 定义要执行的动作,如流程的判断、异步请求
在 store.js 内的 actions 中
// 定义 actions ,要执行的动作,如流程的判断、异步请求const actions ={
increment({commit,state}){
commit('increment')
},
decrement({ commit, state }) { // **通过动作改变的数据,在此处来做判断是否提交**
if (state.count > 5) {
commit('decrement')
}
}
}运行项目
count--.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 内的 actions 中添加 异步 Promise 事件
// 定义 actions ,要执行的动作,如流程的判断、异步请求const actions ={
increment({commit,state}){
commit('increment')
},
decrement({ commit, state }) { // **通过动作改变的数据,在此处来做判断是否提交**
if (state.count > 5) {
commit('decrement')
}
},
incrementAsync({commit,state}){ // 模拟异步操作
var a = new Promise((resolve,reject) => {
setTimeout(() => {
resolve();
}, 3000);
}) // 3 秒之后提交一次 increment ,也就是执行一次 increment
a.then(() => {
commit('increment')
}).catch(() => { console.log('异步操作失败');
})
}
}运行项目
异步.gif
三、获取数据状态
假如我们需要知道数据的奇偶数,那么就需要在 getters 中来判断。
getters 中可以获取经过处理后的数据,从而来判断状态
在 store.js 的 getters 中加入判断奇偶数的方法
var getters={
count(state){ return state.count
},
EvenOrOdd(state){ return state.count%2==0 ? '偶数' : '奇数'
}
}在 App.vue 中加入
<template>
<div id="app">
<button @click="increment">增加</button>
<button @click="decrement">减少</button>
<button @click="incrementAsync">异步增加</button>
<h1>{{count}}</h1>
<!-- 判断奇偶数的方法 这种写法它会自动调用 EvenOrOdd 方法中的返回值,拿到的是个属性 -->
<h1>{{EvenOrOdd}}</h1>
</div></template><script>import {mapGetters,mapActions} from 'vuex'export default { name: 'app', computed:mapGetters([ // 判断奇偶数的方法
'EvenOrOdd', 'count'
]), methods:mapActions([ 'increment', 'decrement', 'incrementAsync'
])
}</script>判断奇偶数.gif
如有不明白之处,还请留言交流,或者直接翻看 API
點(diǎn)擊查看更多內(nèi)容
1人點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦



