VUEX 使用学习四 : action

转载请注明出处:

  action 用于处理异步任务;action,可以操作任意的异步操作,类似于mutations,但是是替代mutations来进行异步操作的。首先mutations中必须是同步方法,如果使用了异步,虽然页面上的内容改变了,但实际上Vuex.Store没有监听到数据的更新

  如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发 Mutation的方式间接变更数据。

1. this.$store.dispatch 是触发actions的第一 种方式

//定义store.js 中定义action
  actions: {
    addAsync(context) {
      setTimeout(()=> {
        context.commit('add')
      },1000)
    }
  }


//在事件方法中通过dispatch触发action
add () {
    //  触发action
    this.$store.dispatch('addAsync')
  }

  触发异步任务携带参数

 mutations: {
   add(state,step) {
    state.count += step
   }
  },
  actions: {
    addAsync(context,step) {
      setTimeout(()=> {
        context.commit('add',step)
      },1000)
    }
  }
//触发action
add () {
    this.$store.dispatch('addAsync',5)
  }

2.触发actions的第二 种方式

  1.从vuex中按需求导入mapState函数

import {maptActions} from 'vuex'

  2. 将指定的mutations函数,映射为当前组件的methods函数

methods:{ ...maptActions(['addAsync']) }

 

  在网上找到一个demo 示例,可参考学习: https://gitee.com/xiangbaxiang/vue-store

 

posted @ 2023-01-18 11:17  香吧香  阅读(78)  评论(0编辑  收藏  举报