Vuex学习小记(action)

action 不能直接变更状态,而是用于提交mutation

mutation只能进行同步操作,而action可进行异步操作.

action接收一个与store实例具有相同属性和方法的context对象作为参数,所以可通过context.commit(‘typeName’)进行提交mutation,也可以通过context.state以及context.getters获取state和getters.但是context并不是store实例本身.

action通过 store.dispatch 触发

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {          //定义mutation
    increment (state) {
      state.count++
    }
  },
  actions: {
      incrementAsync ({ commit }) {  //其中可进行异步操作
        setTimeout(() => {
          commit('increment')      //提交mutation
        }, 1000)
      }
    }
})

store.dispatch('increment')  //触发action

action支持与mutation同样的载荷方式和对象方式进行分发

你在组件中使用 this.$store.dispatch(‘xxx’) 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

组合action( 暂时不太懂 ???? )

actions: {
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

利用 async / await 这个 JavaScript 即将到来的新特性,我们可以像这样组合 action:

// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值