我来为您详细解释这几个代码块之间的关系与运行机制。 Ran tool Read file: mallApp/src/store/modules/vuexStorange.js 现在我来详细解释这几个代码块之间的关系与运行机制:
main.js (应用入口)
↓
store/index.js (Vuex 主 Store)
↓
store/modules/ (各功能模块)
├── user.js (用户模块)
├── login.js (登录模块)
└── ... (其他模块)
↓
pages/home/recent.vue (页面组件)
import store from './store'
Vue.prototype.$store = store
main.js 导入 Vuex storethis.$store 访问const store = new Vuex.Store({
modules,
state: {
allOptions: ''
},
getters: {
allOptions: state => state.allOptions ||
(util.isEmpty(uni.getStorageSync('allOptions')) ? {} : JSON.parse(uni.getStorageSync('allOptions')))
},
mutations: {
// 全局选项
setAllOptions(state, data = {}) {
state.allOptions = data
uni.setStorageSync('allOptions', JSON.stringify(data))
}
},
actions: {
getAllOptions({ commit }) {
// sysBudgetStatus 预算 sysRenovationStatus 装修类型 sysBookingStatus 派单状态
return getOptions({
type: ''
}).then((res) => {
if (res.status === 'success') {
commit('setAllOptions', res.data)
} else {
uni.showToast({
title: res.errors.message,
icon: 'none'
})
}
})
}
}
})
核心特点:
modules 导入各功能模块allOptions)uni.getStorageSync 中各模块独立管理各自的状态:
用户模块 (user.js):
getUser: (state) => {
getState(state, 'user', 'userInfo')
return state.user
},
登录模块 (login.js):
getLoginInfo(state) {
return state.loginInfo || {}
},
通过 vuexStorange.js 实现数据持久化:
export function getState(state, stateName, name) {
if (process.env.NODE_ENV == 'development' && !state[stateName]) {
let userInfo = uni.getStorageSync(name)
if (userInfo) {
state[stateName] = JSON.parse(userInfo)
}
}
}
export function setState(state, userInfo, stateName, name) {
if (process.env.NODE_ENV == 'development') {
uni.setStorageSync(name, JSON.stringify(userInfo))
}
state[stateName] = userInfo
}
特点:
import { mapGetters } from 'vuex'
computed: {
...mapGetters({ userInfo: "getUser",loginInfo:"getLoginInfo" })
},
数据流向:
mapGetters 映射 store 中的 gettersgetUser 来自 user 模块getLoginInfo 来自 login 模块this.userInfo 和 this.loginInfo1. 应用启动
main.js → 初始化 store → 挂载到 Vue 原型
2. 数据获取
getter 调用 → 检查内存状态 → 如果为空则从本地存储恢复
3. 数据更新
action → mutation → 更新内存状态 → 同步到本地存储
4. 组件使用
mapGetters → 响应式获取状态 → 自动更新视图
这种架构非常适合 uni-app 项目的状态管理需求,既保证了数据的一致性,又提供了良好的开发体验。