Vue 中 vuex 的使用
一、内容:
1.vuex 是 vue 中实现“集中式数据管理”的一个 vue 插件。
2.被管理的数据,是组件共享的,任意组件都可以访问管理。
3.vuex 包含三个部分:actions(动作), mutations(加工), state(状态)。
4.工作原理:
(1)组件欲发起动作(即修改数据)。
(2)向vuex中的actions分发(dispatch)动作,
(3)actions向mutations提交(commit)动作;
(4)mutations加工state;
(5)state 发生变化,vuex 渲染组件页面。
注意:在 actions 中,集中处理业务逻辑,或其他准备工作(如,向服务器请求数据)等。
如不需要业务处理,则可以忽略,即组件可以略过 actions 直接向 mutations 提交动作。
5.由 store(仓库) 统一管理 actions, mutations, state,组件只与 store 打交道。
二、安装:
执行命令:cd xxxx(项目目录)
执行命令:npm i vuex@3 【vue2 项目使用 vuex@3, vue3 项目使用最新版vuex】
三、引入‘Vuex 插件库’:
在main.js中添加:
import Vuex from 'vuex';
Vue.use(Vuex);
四、创建 store
在 src 目录下创建目录 store,在目录 store 下创建文件 index.js。
在 index.js 中创建 actions, mutations, state, 并new 一个 store:
//用于构建 vuex 的 store import Vuex from 'vuex'; const actions ={ }; const mutations ={ }; const state ={ }; const store = new Vuex.Store({ actions, mutations, state }); export default store;
五、引入配置好的‘store’,并将其交给 vm:
在 main.js 添加:
import Vue from 'vue';
import Vuex from 'vuex'; import store from './store'; import App from './App.vue'; Vue.config.productionTip = false; Vue.use(Vuex); export default new Vue({ el:'#app', render: h => h(App), store });
六、修改引入顺序
1.需要修改的原因是:
在 main.js 中,import store from './store'; 先于 Vue.use(Vuex); 执行,这将导致 store/index.js 中的 new Vuex.Store() 先于 Vue.use(Vuex); 执行;
而 Vue.use(Vuex); 必须在 new Vuex.Store() 之前。
2.修改的方式:
(1)在 main.js中移除语句:import Vuex from 'vuex'; 和 Vue.use(Vuex);
(2)在目录 store 下 index.js 文件中,添加 import Vue from 'vue'; 在 new Vuex.Store() 之前, 添加语句:Vue.use(Vuex);
(3)index.js 实际为:

//用于构建 vuex 的 store import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const actions ={ }; const mutations ={}; const state ={}; const store = new Vuex.Store({ actions:actions, mutations:mutations, state:state }); export default store;
main.js 实际为:

import Vue from 'vue'; import store from './store'; import App from './App.vue'; Vue.config.productionTip = false; export default new Vue({ el:'#app', render: h => h(App), store });
七、使用
1.组件中使用vuex中的数据: this.$store.state.xxxdata
2.组件中修改vuex中的数据: this.$store.dispatch('actionname', value) 或 this.$store.commit('mutationname', value)
3.import { mapState, mapGetters } from 'Vuex';
computed:{...mapState(['sum'])}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek “源神”启动!「GitHub 热点速览」
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器