如何在 Vue 3 项目中使用 Vuex 进行状态管理?

news/2024/10/4 1:38:46/

在 Vue 3 中使用 Vuex 进行状态管理是一个很好的实践,特别是在涉及到多个组件间共享状态的情况。下面是如何在 Vue 3 项目中设置和使用 Vuex 的教程,包括 state, mutations, actions, getters 的概念及其用途。

1. 安装 Vuex

首先确保你的项目已经安装了 Vue CLI 并且是 Vue 3 版本。然后安装 Vuex 4.x:

npm install vuex@next --save

或使用 Yarn:

yarn add vuex@next --save

2. 初始化 Vuex Store

在 Vue 3 中,Vuex 的实现方式略有不同,主要在于使用 Composition API。创建一个名为 store.js 的文件,并初始化 Vuex:

javascript">import { createStore } from 'vuex';const store = createStore({state: {count: 0,},mutations: {increment(state) {state.count++;},},actions: {increment(context) {context.commit('increment');},},getters: {doubleCount(state) {return state.count * 2;},},
});export default store;

3. 配置 Vue 应用来使用 Vuex Store

在你的入口文件(通常是 main.jsmain.ts)中配置 Vuex store:

javascript">import { createApp } from 'vue';
import App from './App.vue';
import store from './store';const app = createApp(App);
app.use(store);
app.mount('#app');

4. 在 Vue 组件中使用 Vuex

使用 State

使用 Composition API 来访问 Vuex 中的 state:

<template><div>{{ count }}</div>
</template><script setup>javascript">
import { useStore } from 'vuex';const store = useStore();
const count = store.state.count;
</script>
使用 Mutations

Mutations 用来同步更新状态:

<template><button @click="increment">Increment</button>
</template><script setup>javascript">
import { useStore } from 'vuex';const store = useStore();function increment() {store.commit('increment');
}
</script>
使用 Actions

Actions 提供了一个异步操作的场所,通常用来处理如网络请求等异步操作:

<template><button @click="incrementAsync">Increment Async</button>
</template><script setup>javascript">
import { useStore } from 'vuex';const store = useStore();async function incrementAsync() {await store.dispatch('increment', { amount: 5 });
}
</script>
使用 Getters

Getters 提供了对状态的派生数据进行计算的功能:

<template><div>{{ doubleCount }}</div>
</template><script setup>javascript">
import { useStore } from 'vuex';const store = useStore();
const doubleCount = store.getters.doubleCount;
</script>

5. 总结

  • State: 存储数据的地方,所有组件都可以访问这些数据。
  • Mutations: 更新 state 的唯一方法,并且必须是同步函数。
  • Actions: 提交 mutation 的方法,可以包含任意异步操作。
  • Getters: 对 state 中的数据进行加工处理,返回新的衍生数据。

6. Vuex 辅助函数

在 Vue 3 中,你可以使用 Vuex 的组合式 API 来管理状态,这包括 useStoremapStatemapGettersmapActionsmapMutations 等辅助函数。然而,在 Vue 3 中,推荐使用 setup 函数和组合式 API (Composition API) 来组织逻辑。

useStore

useStore 是一个组合式 API 函数,返回当前 store 的引用。

import { useStore } from 'vuex';export default {setup() {const store = useStore();return { store };}
}
mapState

mapState 用于将状态映射到组合式 API 的返回对象。

import { mapState } from 'vuex';export default {setup() {const { count } = mapState(['count'])();return { count };}
}
mapGetters

mapGetters 用于将 getter 映射到组合式 API 的返回对象。

import { mapGetters } from 'vuex';export default {setup() {const { doubleCount } = mapGetters(['doubleCount'])();return { doubleCount };}
}
mapMutations

mapMutations 用于将 mutations 映射到组合式 API 的方法。

import { mapMutations } from 'vuex';export default {setup() {const { increment } = mapMutations(['increment']);return { increment };}
}
mapActions

mapActions 用于将 actions 映射到组合式 API 的方法。

import { mapActions } from 'vuex';export default {setup() {const { fetchCount } = mapActions(['fetchCount']);return { fetchCount };}
}

使用示例

假设你有一个名为 counter 的模块,并且你想在组件中使用它:

// store/modules/counter.js
const state = {count: 0,
};const getters = {doubleCount(state) {return state.count * 2;},
};const mutations = {increment(state) {state.count++;},
};const actions = {async fetchCount({ commit }) {// 模拟异步操作await new Promise(resolve => setTimeout(resolve, 1000));commit('increment');},
};export default {namespaced: true,state,getters,mutations,actions,
};

在你的 Vue 3 组件中,你可以这样使用:

<template><div>{{ count }}<button @click="increment">Increment</button><button @click="fetchCount">Fetch Count</button></div>
</template><script>
import { useStore } from 'vuex';
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';export default {setup() {const store = useStore();const { count } = mapState({ count: state => state.counter.count })();const { doubleCount } = mapGetters({ doubleCount: 'counter/doubleCount' })();const { increment } = mapMutations({ increment: 'counter/increment' });const { fetchCount } = mapActions({ fetchCount: 'counter/fetchCount' });return {count,doubleCount,increment,fetchCount,};},
};
</script>

注意事项

  • 使用 mapState, mapGetters, mapMutations, mapActions 时,你需要确保它们作为函数被调用,并且返回的对象需要被解构赋值给组件中的响应式变量。
  • 如果你的模块是命名空间化的,你需要正确地引用它们。
  • 在 Vue 3 中,Vuex 的辅助函数需要配合 setup 函数使用,并且通常与 Composition API 一起使用。

这些辅助函数可以帮助你在 Vue 3 中更方便地使用 Vuex 来管理状态,同时也让代码更具可读性和可维护性。


http://www.ppmy.cn/news/1533412.html

相关文章

C++ 游戏开发

C游戏开发 C 是一种高效、灵活且功能强大的编程语言&#xff0c;因其性能和控制能力而在游戏开发中被广泛应用。许多著名的游戏引擎&#xff0c;如 Unreal Engine、CryEngine 和 Godot 等&#xff0c;都依赖于 C 进行核心开发。本文将详细介绍 C 在游戏开发中的应用&#xff0…

代码随想录算法训练营Day20 | 235. 二叉搜索树的最近公共祖先、701.二叉搜索树中的插入操作、450.删除二叉搜索树中的节点

目录 235. 二叉搜索树的最近公共祖先 701.二叉搜索树中的插入操作 450.删除二叉搜索树中的节点 235. 二叉搜索树的最近公共祖先 题目 235. 二叉搜索树的最近公共祖先 - 力扣&#xff08;LeetCode&#xff09; 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先…

Redis-持久化机制

Redis持久化方式 rdb -> 全量 aof -> 增量 也可以两种同时开启&#xff0c;混合持久化(4.0 后) rdb 简介 配置文件 redis 6.0.16 及其以下 redis 6.2 7.0 配置说明 有两种触发方式&#xff1a;手动&#xff0c;自动 修改 save 5 2dir /myredis/dump (储存的文件夹需…

c# iTextSharp 读取PDF

安装 iTextSharp&#xff1a; 可以通过 NuGet 包管理器安装 iTextSharp&#xff1a; Install-Package itext7创建 PDF 文件&#xff1a; using System; using System.IO; using iText.Kernel.Pdf; using iText.Layout; using iText.Layout.Element;class Program {static voi…

如何从 Windows 11/10/8.1/8/7 中恢复已删除的视频

不小心删除了视频或格式化了 SD 卡/硬盘&#xff1f;没有备份已删除的视频&#xff1f;不要担心&#xff0c;我们有一个解决方案 可以恢复 Windows 11、10 中已删除的视频并处理这种可怕的情况。 但是&#xff0c;在详细介绍如何恢复已删除的视频和视频恢复应用程序之前&#…

《PMI-PBA认证与商业分析实战精析》第4章 商业分析规划

第4章 商业分析规划 本章主要内容&#xff1a; 商业分析规划概述 干系人分析 创建商业分析计划 规划商业分析工作 本章涵盖的考试重点: 商业分析规划的三项活动 商业分析规划的三个可交付成果 商业分析规划相关活动的技术 商业分析计划的内容 预测型、适应型和混合型…

UNI-SOP应用场景(1)- 纯前端预开发

在平时新项目开发中&#xff0c;前端小伙伴是否有这样的经历&#xff0c;hi&#xff0c;后端小伙伴们&#xff0c;系统啥时候能登录&#xff0c;啥时候能联调了&#xff0c;这是时候往往得到的回答就是&#xff0c;再等等&#xff0c;我们正在搭建系统呢&#xff0c;似曾相识的…

小徐影院:探索Spring Boot的影院管理

第二章开发技术介绍 2.1相关技术 小徐影城管理系统是在Java MySQL开发环境的基础上开发的。Java是一种服务器端脚本语言&#xff0c;易于学习&#xff0c;实用且面向用户。全球超过35&#xff05;的Java驱动的互联网站点使用Java。MySQL是一个数据库管理系统&#xff0c;因为它…