Vuex ---Actions 异步修改

文章介绍了Vuex中Actions的作用,它用于处理异步操作,通过提交mutation来间接修改state。在组件内,可以通过dispatch调用Actions,而在CompositionAPI中,可借助useStore来调用Actions进行状态管理。
摘要由CSDN通过智能技术生成

Vuex ---Actions 异步修改

actions

action提交的是mutation,而不是直接变更状态
action可以包含任意异步操作

actions里面是放的我们的函数,函数里面的参数context,可以帮我们提交mutations
**逻辑梳理:**到时候在组件内部,调用actions之后,actions里面又去调用mutations,而mutations又去修改了state。

    mutations:{
      increate(state){ //payload:携带参数
         state.counter++
      }
    },
    actions:{
       //放函数de,
        increateAction(context){
            context.commit("increate")
        }
    }

如何在组件中调用actions?

<template>
    <div>
   <button @click="increatet"></button>
    </div>
</template>
<script>
export default {
   methods:{
    // 在点击的时候去分发我们的actions
       increatet(){
        this.$store.dispatch("increateAction")
       }
   }
}
</script>

Actions 在compositionAPI 的使用方法:

import {useStore} from 'vuex'
import {onMounted} from "vue"
export default {
setup(){
    const store=useStore()
    onMounted(() => {
        store.dispatch("getHomeMutidata")
    }),
    return{
 
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue.js是一个流行的JavaScript框架,它允许您构建动态Web应用程序。Vuex是一个专为Vue.js应用程序开发的状态管理模式。它允许您在应用程序中管理和维护状态,例如用户信息、购物车、主题等。Vuex将状态存储在一个集中的存储库中,称为store。Vuex的核心概念包括state、mutations、actions和getters。 - state:存储应用程序级别的状态,可以通过store.state访问。 - mutations:用于更改状态的函数,必须是同步函数。可以通过store.commit方法调用。 - actions:用于处理异步操作的函数,可以包含任意异步操作。可以通过store.dispatch方法调用。 - getters:用于从store中获取状态的函数,可以通过store.getters访问。 下面是一个简单的示例,演示如何在Vue.js应用程序中使用Vuex: 1.安装Vuex ```shell npm install vuex --save ``` 2.创建store ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount: state => { return state.count } } }) export default store ``` 3.在Vue组件中使用store ```javascript <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters([ 'getCount' ]) }, methods: { ...mapActions([ 'increment', 'incrementAsync' ]) } } </script> ``` 在上面的示例中,我们创建了一个名为count的状态,并定义了一个名为increment的mutation和一个名为incrementAsync的action。我们还定义了一个名为getCount的getter,用于从store中获取count状态。在Vue组件中,我们使用mapGetters和mapActions帮助程序将getter和action映射到组件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Clover‘s Blog

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

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

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

打赏作者

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

抵扣说明:

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

余额充值