vue进一步深入

我们都知道如何通过一些简单的动作来改变 store.js 中的数据对象,在实际工作中,这是完全无法满足工作需求的,所以我来说说如何做一些简单的流程判断。

一、比如说我现在有这么个需求,当 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.jsgetters 中加入判断奇偶数的方法

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

如果有什么我讲的不明白的地方,大家可以留言,或者我所说不对的地方,欢迎指出,避免大家以后继续踩坑.

posted on 2018-03-29 12:09  大风hhh  阅读(151)  评论(0编辑  收藏  举报

导航