[聚合文章] Vuex 提升

Vue.js 1900-01-01 10 阅读
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('异步操作失败');        })
                

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。