如果本篇有看不明白的地方,请移步上一篇: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'