1
This commit is contained in:
128
utils/store.js
Normal file
128
utils/store.js
Normal file
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* 全局状态管理器
|
||||
* 提供应用级数据管理和状态同步
|
||||
*/
|
||||
|
||||
class Store {
|
||||
constructor() {
|
||||
this.state = {
|
||||
userInfo: null,
|
||||
isLogin: false,
|
||||
favoriteCourses: [],
|
||||
gpaCourses: [],
|
||||
schedule: {},
|
||||
countdowns: [],
|
||||
settings: {
|
||||
theme: 'light',
|
||||
notifications: true,
|
||||
language: 'zh-CN'
|
||||
}
|
||||
}
|
||||
this.listeners = []
|
||||
this.init()
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化:从本地存储恢复状态
|
||||
*/
|
||||
init() {
|
||||
try {
|
||||
const savedState = wx.getStorageSync('appState')
|
||||
if (savedState) {
|
||||
this.state = { ...this.state, ...savedState }
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('状态初始化失败:', e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取状态
|
||||
*/
|
||||
getState(key) {
|
||||
if (key) {
|
||||
return this.state[key]
|
||||
}
|
||||
return this.state
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置状态
|
||||
*/
|
||||
setState(key, value) {
|
||||
if (typeof key === 'object') {
|
||||
// 批量更新
|
||||
this.state = { ...this.state, ...key }
|
||||
} else {
|
||||
this.state[key] = value
|
||||
}
|
||||
|
||||
this.notify()
|
||||
this.persist()
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅状态变化
|
||||
*/
|
||||
subscribe(listener) {
|
||||
this.listeners.push(listener)
|
||||
return () => {
|
||||
const index = this.listeners.indexOf(listener)
|
||||
if (index > -1) {
|
||||
this.listeners.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知所有订阅者
|
||||
*/
|
||||
notify() {
|
||||
this.listeners.forEach(listener => {
|
||||
try {
|
||||
listener(this.state)
|
||||
} catch (e) {
|
||||
console.error('状态通知失败:', e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 持久化到本地存储
|
||||
*/
|
||||
persist() {
|
||||
try {
|
||||
wx.setStorageSync('appState', this.state)
|
||||
} catch (e) {
|
||||
console.error('状态持久化失败:', e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空状态
|
||||
*/
|
||||
clear() {
|
||||
this.state = {
|
||||
userInfo: null,
|
||||
isLogin: false,
|
||||
favoriteCourses: [],
|
||||
gpaCourses: [],
|
||||
schedule: {},
|
||||
countdowns: [],
|
||||
settings: {
|
||||
theme: 'light',
|
||||
notifications: true,
|
||||
language: 'zh-CN'
|
||||
}
|
||||
}
|
||||
this.persist()
|
||||
this.notify()
|
||||
}
|
||||
}
|
||||
|
||||
// 创建全局实例
|
||||
const store = new Store()
|
||||
|
||||
module.exports = {
|
||||
store
|
||||
}
|
||||
Reference in New Issue
Block a user