action的基本定义

■官方强调了不要在Mutations中进行异步操作

  • 但是某些情况,我们确实希望在vuex中进行一些异步操作,比如网络请求,必然是异步的,这个时候怎么处理呢?
  • action类似于mutation,但是是用来代替mutation进行异步操作的

action的基本使用

■这里使用setTimeout来模拟异步操作,在一秒后修改state中info的值

  • Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation
  • 也可以通过 context.state 和 context.getters 来获取 state 和 getters

■stroe下index.js中的代码

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
            info:'xiu',
  },
  mutations: {
    mUpdateInfo(state){
      state.info = 'fan'
    }
  },
  actions: {
    aUpdateInfo(context){
        setTimeout(() => {、
            //提交到mutation进行处理
            context.commit('mUpdateInfo')
        },1000)        
    }
  },
})

■在actions中定义异步操作的函数

  • 但前面提到过,修改state中的数据要在mutations中进行
  • 所以请求完成后action通过commit提交到mutation进行处理

■组件中的代码

<template>
  <div class="about">
    <h1>This is an about page</h1>
            <h2>{{$store.state.info}}</h2>
            <button @click="update()">修改</button>
  </div>
</template>

<script>
  export default{
    name: 'About',
    methods:{
        update(){
            //通过dispatch提交到action
            this.$store.dispatch("aUpdateInfo")
        },
    }
  }
</script>

■Actions 支持和mutations同样的载荷方式和对象方式进行分发

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

■Action 通常是异步的,那么如何知道 action 什么时候结束呢?

  • 首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且store.dispatch 仍旧返回 Promise --->(Promise的使用
  actions: {
    aUpdateInfo(context){
        return new Promise((resolve,reject) => {
            setTimeout(() => {
                context.commit('mUpdateInfo')
                resolve("请求完成")
            },1000)
        })
    }
  },

■现在可以在组件中通过.then()知道请求生么时候完成

        update(){
            this.$store
                 .dispatch("aUpdateInfo")
                 .then(res => {
                    console.log(res)
                 })
        },

其他vuex文章

Vuex概念和作用解析
vuex-mutation同步函数
vuex-getters的使用
vuex-actions异步函数
vuex-modules的使用