Vue3中使用Vuex需严格遵循state→mutations→actions→getters链路;创建store须用vuex@4.x并使state为函数;main.js中挂载store须在mount前;组件内读写状态需通过useStore()配合computed、commit、dispatch。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

在Vue3项目中编写Vuex状态管理逻辑,需严格遵循“state定义数据→mutations同步修改→actions处理异步→getters派生计算”的链路,跳过任一环节会导致响应失效或调试困难。
创建Vuex Store实例
在src/store/index.js中新建文件,使用createStore初始化store对象。注意必须用vuex@4.x版本(即vuex@next),Vue3不兼容vuex@3。
导入createStore后,直接导出store实例:import { createStore } from 'vuex'; export default createStore({ state() { return { count: 0, userInfo: null }; } });
【state必须是函数】否则在多实例场景下会共享引用,导致状态污染。
立即学习“前端免费学习笔记(深入)”;
配置Vue应用接入Store
打开main.js(或main.ts),引入刚创建的store,并通过app.use(store)挂载。
确保挂载时机在app.mount('#app')之前,否则组件内useStore()将返回undefined。
在组件中读取与修改状态
使用Composition API时,先调用useStore()获取store实例。
将静态 Vue 页面(index.vue)改造为动态页面(Custom.vue);稿源仅限 index.vue、其引用的 CSS 与资源路径,禁止参考仓库内其他文件。Invoke when user wants to transform a static Vue page into a dynamic data-driven page with Element UI components.
读取state:const count = computed(() => store.state.count) —— 必须包裹在computed中,否则失去响应性。
提交mutation:store.commit('increment') —— mutation名必须与store中定义的key完全一致,大小写敏感。
触发action:store.dispatch('fetchUser') —— action可接收payload参数,如dispatch('login', { username, password })。
定义核心逻辑模块
第一步:在store对象中补充mutations字段,每个方法接收state为第一参数,仅允许同步操作。
第二步:添加actions字段,每个函数接收{ commit, dispatch, state }解构对象,支持await、setTimeout等异步流程。
第三步:加入getters字段,用箭头函数或完整函数声明,例如doubleCount: state => state.count * 2,其返回值自动缓存。
第四步:若项目规模扩大,按功能拆分modules,每个module可独立拥有state、mutations、actions和getters。

















