uni-app中需手动创建并挂载Vuex Store实例,路径必须为src/store/index.js,用new Vuex.Store()构造,main.js中显式传入store选项,否则this.$store为undefined;修改state必须通过commit mutations,读取推荐mapState或computed。

uni-app 项目里直接用 Vuex,不需要 npm install vuex,但必须手动创建 store 实例并挂载到 Vue 实例,否则所有组件访问 this.$store 都会是 undefined。
store/index.js 必须用 new Vuex.Store() 显式构造
很多人写成 export default { state: {} },这只是一个普通对象,不是 Vuex store,this.$store 无法识别。正确做法是:
-
import Vuex from 'vuex'后必须调用Vuex.Store构造函数 - 路径必须是
src/store/index.js(或项目根目录下的store/index.js),其他位置如store/main.js不会被自动识别 - 如果拆模块,
modules/user.js必须export default一个含state(不能是函数)、mutations等字段的对象
最小可用示例:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { token: '' },
mutations: {
setToken(state, token) {
state.token = token
}
}
})
main.js 中必须显式传入 store 选项
不挂载,this.$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.
- 漏写
store字段:new Vue({ render: h => h(App) })—— 缺失挂载 - 路径写错:比如
import store from '@/store'却没配 webpack alias - 在 Vue3 项目中误用 Vue2 写法(或反之):uni-app Vue2 项目用
new Vuex.Store;Vue3 项目应改用createStore,且挂载方式不同
main.js 关键片段(Vue2):
import Vue from 'vue'
import App from './App.vue'
import store from './store' // ← 路径必须对
Vue.config.productionTip = false
const app = new Vue({
store, // ← 必须显式传入
render: h => h(App)
})
app.$mount()
修改 state 必须走 commit,不能直接赋值
直接写 this.$store.state.count = 5 不会触发响应式更新、不会被 vue-devtools 捕获、getters 也不会重算。这是最常踩的坑。
- 同步修改只能通过
mutations:在组件中调用this.$store.commit('setCount', 5) - 异步操作必须走
actions:比如登录后请求接口再存 token,得用this.$store.dispatch('login', credentials) - 读取推荐用
mapState或computed,不要在data()里缓存副本,否则 store 更新后副本不会变
跨页面使用要注意初始化时机和持久化衔接
App.vue 的 onLaunch 是最早钩子,但首页可能在 store 初始化完成前就已渲染,导致 mapState 取到空值。建议:
-
state初始值设为合理默认(如userInfo: null),而非false或空字符串,避免“未加载完就判断失败” - 需要持久化的字段(如 token、用户信息),应在
mutations里同步调用uni.setStorageSync,而不是只改内存状态 - nvue 页面也能用
$store,但前提是它由 vue 页面引入或通过uni.navigateTo正常跳转,否则可能拿不到实例
真正容易被忽略的是:Vuex 在 uni-app 里不是“可选插件”,而是中大型项目避免状态混乱的底线方案。一旦开始跨页面共享登录态、购物车、主题色等,绕过它只会让问题在调试时更难定位。

















