vuex actions、mapActions、...mapActions(五)

目录

actions 和 mutations 区别

action 注册

actions 触发

购物车示例:调用异步 API 和分发多重 mutations

在组件中触发 actions

组合 actions


 

  • actions 和 mutations 的区别?
  • actions 中的事件第一个参数是 context,第二个参数是 payload 外界传入的值;在 method 事件中通过 this.$store.dispatch() 触发,触发传入的参数有 4 种形式
  • actions 中的函数使用对象解构赋值、对象解构赋值无顺序要求:第一个参数解构赋值 {commit, dispath, getters, rootGetters, rootState, state} 
  • actions 执行异步操作

actions 和 mutations 区别

  • actions 类似 mutation,不同在于
    • actions 提交 mutations,不能直接变更状态
    • actions 可以包含任意异步操作,mutations 包含的是同步操作
    • actions 通过 dispatch 触发,mutations 通过 commit 触发

action 注册

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})
  • actions 接收 2 个参数,第一个参数是 context 对象,第二个参数是外界传入的值 payload
  • actions 函数接收一个与 store 实例具有相同方法和属性的 context 对象
  • 通过 context.commit 提交 mutations
  • 也通过 context.state 和 context.getters 来获取 state 和 getters
  • 使用 ES2015 参数解构简化代码
actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

actions 触发

// actions 通过 this.$store.dispatch() 触发
this.$store.dispatch('increment')
  • action 内部执行异步操作
actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}
  • actions 支持同样的载荷方式和对象方式进行分发
// 以载荷形式分发
this.$store.dispatch('incrementAsync', {
  amount: 10
})

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

购物车示例:调用异步 API 和分发多重 mutations

actions: {
  checkout ({ commit, state }, products) {
    // 把当前购物车的物品备份起来
    const savedCartItems = [...state.cart.added]
    // 发出结账请求,然后乐观地清空购物车
    commit(types.CHECKOUT_REQUEST)
    // 购物 API 接受一个成功回调和一个失败回调
    shop.buyProducts(
      products,
      // 成功操作
      () => commit(types.CHECKOUT_SUCCESS),
      // 失败操作
      () => commit(types.CHECKOUT_FAILURE, savedCartItems)
    )
  }
}

进行一系列异步操作,通过提交 mutation 来记录 action 产生的副作用(即状态变更)。

在组件中触发 actions

  • 组件中使用 this.$store.dispatch('xxx') 触发 actions
  • 也使用 mapActions 辅助函数将组件 methods 映射为 this.$store.dispatch() 调用
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')`
    })
  }
}

组合 actions

  • this.$store.dispatch() 可以处理被触发 actions 处理函数返回的 Promise
  • 并且 this.$store.dispatch() 仍旧返回 Promise
// @/store/index.js
actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation') // 在 actions 中使用 commit 提交 mutations 中定义的事件
        resolve('触发成功')
      }, 1000)
    })
  }
}
// 页面中通过
this.$store.dispatch('actionA').then((res) => {
  console.log(res)
})

在另外一个 actions 中也可以:

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

 使用 async / await 可以如下组合 action:

// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值