uni-app 不用 npm install vuex,因已内置;vue 2 用 new vuex.store() 并 vue.use(vuex),vue 3 必须用 createstore 且 app.use(store);store/index.js 统一用 createstore 写法兼容双模式,模块化拆分、避免 state 存函数/date,页面中 vue 2 用 this.$store,vue 3 用 usestore(),action 中需显式 commit mutation,命名空间开启后需加模块前缀。

uni-app 里要不要 npm install vuex
不用装,uni-app(2.x 和 3.x)都已内置 vuex,直接 import 就行。强行 npm install vuex 反而可能引发版本冲突,尤其在 Vue 3 模式下会报 vuex is not a constructor 这类错误。
- Vue 2 模式:用
new Vuex.Store({}),需先Vue.use(Vuex) - Vue 3 模式(推荐):必须用
createStore,且不能调用Vue.use—— 否则控制台警告“app.use() is called with an unregistered plugin” - 项目创建时若选的是“Vue 3 + Composition API”模板,
main.js里是createApp,那store必须通过app.use(store)注入,不是挂到Vue.prototype
store/index.js 怎么写才兼容 Vue 2 / Vue 3
别写两套,统一用 Vue 3 风格写法,它在 Vue 2 模式下也能跑(uni-app 做了兼容层)。关键点是:导出一个 store 实例,而不是 export default new Vuex.Store(...) 这种老写法。
- 路径必须是
store/index.js,uni-app 会自动识别这个入口 - 用
createStore而非new Vuex.Store:import { createStore } from 'vuex' - 模块化建议立刻上:
modules目录下拆user.js、cart.js,避免index.js膨胀成千行大文件 - 别在
state里放函数或 Date 对象——它们不会响应式更新,getters里也别直接调用异步方法
页面里怎么读写 store 数据(Vue 2 vs Vue 3 写法差异)
写法不统一是报错高发区。Vue 2 页面(.vue 里有 export default 对象)用 this.$store;Vue 3 页面(setup())必须用 useStore(),否则 undefined。
- Vue 2 页面中:
computed: { count() { return this.$store.state.count } },methods: { inc() { this.$store.commit('increment') } } - Vue 3 页面中:
import { useStore } from 'vuex'; const store = useStore(); console.log(store.state.count) - 别在
setup()里用this.$store—— 它根本不存在,也不会报错,只是静默失效 -
mapState/mapActions在 Vue 3 的setup中不支持,必须手写store.state.xxx或封装成组合函数
为什么 dispatch 了 action,state 却没更新
最常见原因是 action 里没正确 commit mutation,或者 mutation 名写错了大小写(Vuex 区分大小写),还有就是异步请求后忘了 commit。
- 检查 mutation 名是否和
commit('xxx')完全一致,比如写了commit('SET_USER'),但定义的是setUser—— 不匹配 - 异步 action 中,
setTimeout或uni.request后必须显式commit,不能只改state(Vuex 不允许直接改 state) - 如果用了模块(
modules),默认命名空间是关闭的,commit('xxx')只能访问根 mutation;开启命名空间后,必须写commit('user/setName') - 调试技巧:在 mutation 里加
console.log('mutate:', state),确认是否真被触发
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










