Vuex的核心概念:Action,问题呈现:计时器案例,定义Action,触发Action,触发actions异步任务时携带参数,触发actions的第二种方式 ,

本文介绍了在Vue.js中,如何使用Vuex进行状态管理,强调了在mutations中不能处理异步代码,转而通过actions处理异步任务。同时讲解了actions的定义、如何触发action以及两种常见的调用方式:通过`dispatch`携带参数和使用`mapActions`映射到组件方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.问题呈现:计时器案例

得出结论:在mutations函数中不能写异步的代码。

此时我们就引出了Action

Action用于处理异步任务。

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

2.定义Action

const store=new Vuex.Store({
    state:{
        count:100
    },
    mutations:{
        // 这里的step接收传递过来的参数
        add(state){
            state.count++
        }
    },
    actions:{
        // 定义了一个新的函数addAsync
        addAsync(context){
            setTimeout(()=>{
                context.commit('add')
                //这里的commit只能调用mutations中的函数
            },1000)
        }
    }
})

3.触发Action

  //触发Action
  methods:{
    Handler1(){
      //在调用dispatch函数
      this.$store.dispatch('addAsync')
    }
  }

效果图:

 

4.触发actions异步任务时携带参数:

1.定义actions
const store=new Vuex.Store({
    state:{
        count:100
    },
    mutations:{
        // 这里的step接收传递过来的参数
        add(state,step){
            state.count+=step
        }
    },
    actions:{
        // 定义了一个新的函数addAsync
        addAsync(context,step){
            setTimeout(()=>{
                context.commit('add',step)
                //这里的commit只能调用mutations中的函数
            },1000)
        }
    }
})
 2.触发actions
 methods:{
    Handler1(){
      //在调用dispatch函数
      this.$store.dispatch('addAsync',5)
    }
  }

效果图:

5.触发actions的第二种方式 

//1.从vuex中按需导入mapActions函数
import {mapActions} from 'vuex'

通过刚才导入的mapActions函数,将需要的actions函数,映射为当前组件的methods方法:

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

 效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

头顶一只喵喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值