Vuex--actions--使用/教程/实例

本文通过实例介绍Vue.js状态管理库Vuex中的actions组件。详细解释了actions如何用于执行异步操作并最终通过mutations更新state,包括直接使用及通过mapActions辅助函数使用的不同方式。

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

原文网址:Vuex--actions--使用/教程/实例_IT利刃出鞘的博客-CSDN博客

简介

说明

本文用示例介绍Vuex的五大核心之一:actions。

官网

Action | Vuex

API 参考 | Vuex

actions概述

说明

Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。

特点

  1. 异步操作,通过mutations来改变state。
  2. 不能直接改变state里的数据。
  3. 包含多个事件回调函数的对象。
  4. 执行方式:通过执行 commit()来触发 mutation 的调用, 间接更新 state
  5. 触发方式: 组件中: $store.dispatch(‘action 名称’, data1)
  6. 可以包含异步代码(例如:定时器, 请求后端接口)。

用法

直接使用

this.$store.dispatch('actions方法名', 具体值)        // 不分模块
this.$store.dispatch('模块名/actions方法名', 具体值) // 分模块

mapActions

import { mapActions } from 'vuex'
export default {
    computed: {
        // 不分模块
        ...mapActions(['actions方法名'])          

        // 分模块,不改方法名
        ...mapActions('模块名', ['actions方法名'])
        
        // 分模块,不改方法名
        ...mapActions('模块名',{'新actions方法名': '旧actions方法名'})
    }
}

示例

 CounterStore.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
const counterStore = new Vuex.Store(
    {
        state: {
            count: 10
        },

        getters: {
            doubleCount(state) {
                return state.count * 2;
            }
        },

        mutations: {
            increment(state) {
                state.count++;
            },
            decrement(state) {
                state.count--;
            },
            // 带参数
            addNumber(state, param1) {
                state.count += param1;
            },
        },

        actions: {
            asyncIncrement(context) {
                console.log('CounterStore=> action: asyncIncrement');
                setTimeout(() => {context.commit('increment')}, 1000)
            },

            asyncAddNumber(context, n) {
                console.log('CounterStore=> action: asyncAddNumber');
                setTimeout(() => {context.commit('addNumber', n)}, 1000)
            }
        }
    }
);

export default counterStore;

Parent.vue(入口组件)

<template>
  <div class="outer">
    <h3>父组件</h3>
    <component-a></component-a>
    <component-b></component-b>
  </div>
</template>

<script>
import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";

export default {
  name: 'Parent',
  components: {ComponentA, ComponentB},
}
</script>

<style scoped>
.outer {
  margin: 20px;
  border: 2px solid red;
  padding: 20px;
}
</style>

ComponentA.vue(异步修改vuex的数据) 

<template>
  <div class="container">
    <h3>ComponentA</h3>
    <button @click="thisAsyncIncrement">异步加1</button>
    <button @click="thisAsyncAddNumber">异步增加指定的数</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cnt: 5
    }
  },
  methods:{
    thisAsyncIncrement() {
      this.$store.dispatch('asyncIncrement')
    },
    thisAsyncAddNumber() {
      this.$store.dispatch('asyncAddNumber', this.cnt)
    }
  }
}
</script>

<style scoped>
.container {
  margin: 20px;
  border: 2px solid blue;
  padding: 20px;
}
</style>

ComponentB.vue(读取vuex的数据) 

<template>
  <div class="container">
    <h3>ComponentB</h3>
    <div>计数器的值:{{thisCount}}</div>
    <div>计数器的2倍:{{thisDoubleCount}}</div>
  </div>
</template>

<script>
export default {
  computed:{
    thisCount() {
      return this.$store.state.count;
    },
    thisDoubleCount() {
      return this.$store.getters.doubleCount;
    },
  }
}
</script>

<style scoped>
.container {
  margin: 20px;
  border: 2px solid blue;
  padding: 20px;
}
</style>

 路由(router/index.js)

import Vue from 'vue'
import Router from 'vue-router'
import Parent from "../components/Parent";

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/parent',
      name: 'Parent',
      component: Parent,
    }
  ],
})

测试

访问: http://localhost:8080/#/parent

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

IT利刃出鞘

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

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

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

打赏作者

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

抵扣说明:

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

余额充值