vuex4之Actions

  1. mutations中所有的代码都是同步代码
  2. 都有的状态的改变都应该在mutations中改变

但是遇到异步请求怎么办?

  1. actions中可以写任何的异步代码
  2. 但是actions不能修改状态,最终状态的修改还是在mutations中修改状态
  3. 所以定义的action中传递的参数是一个上下文对象,在这个上下文对象中有一个commit方法,专门用来提交到mutation中修改状态

例子

模板

<script>
import { mapState } from 'vuex'

export default {
    methods: {
        incrementCount(num) {
            this.$store.dispatch("incrementAsync", num).then(data => {
                console.log(data);
            })
        }
    },
    computed: {
        ...mapState(["count"]),
    }
}
</script>

<template>
    <p>count:{{ count }}</p>
    <button @click="incrementCount(2)">changeCount</button>
</template>

创建store

import { createStore } from "vuex";

// 创建一个新的 store 实例
const store = createStore({
    state() {
        return {
            count: 0
        };
    },
    actions: {
        incrementAsync(context, n) {
            // context中有commit state getters 等
            return new Promise(resolve => {
                setTimeout(() => {
                    context.commit("increment", n)
                    resolve("执行成功")
                }, 1000)
            })
        }
    },
    mutations: {
        increment(state, n) {
            state.count = state.count + n
        }
    }
});

export default store;

效果
在这里插入图片描述

对于代码的解释

  1. 我们出发的action返回什么值,我们就能拿到什么值,比如例子中我们返回的是promise,所以我们可以调用then方法
  2. 触发action,除了例子中的方法,还有其他的两种形式
// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})
  1. action的第一个参数是一个对象,对象中有commit state getters

mapActions

mapActions是一个语法糖,他可以直接将actions映射到组件中

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')`
    })
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值