vuex深入学习 --- Action

6 篇文章 0 订阅

vuex深入学习 — Action

特性:

  1. Action 提交的是 mutation,而不是直接变更状态。

  2. Action 可以包含任意异步操作

  3. 适合多个Mutation的操作

    const store = new Vuex.Store({
    state: {
    count: 0
    },
    mutations: {
    increment (state) {
    state.count++
    }
    },
    actions: {
    // 这里 context 可以使用对象解构 {commit}
    increment (context) {
    context.commit(‘increment’)
    }
    }
    })

调用: this.$store.dispatch('increment')
载荷形式: this.$store.dispatch('incrementAsync', {amount: 10})
对象形式: this.$store.dispatch({type: 'incrementAsync',amount: 10})

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

1.mapActions 辅助函数

    import { mapActions } from 'vuex'

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

2.组合Action
store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise

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

使用async/await

      // 假设 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、付费专栏及课程。

余额充值