131 lines
2.8 KiB
JavaScript
131 lines
2.8 KiB
JavaScript
import { reactive, ref, watch } from 'vue';
|
||
import { storage } from '../utils/storage';
|
||
|
||
|
||
|
||
// 防抖函数
|
||
const debounce = (fn, delay = 300) => {
|
||
let timer = null
|
||
return function (...args) {
|
||
if (timer) clearTimeout(timer)
|
||
timer = setTimeout(() => {
|
||
fn.apply(this, args)
|
||
}, delay)
|
||
}
|
||
}
|
||
|
||
// 定义应用的全局状态
|
||
export const store = reactive({
|
||
// 用户信息
|
||
userInfo: storage.get('userInfo') || null,
|
||
|
||
// 应用设置
|
||
settings: storage.get('settings') || {
|
||
theme: 'light',
|
||
language: 'zh-CN',
|
||
notifications: true
|
||
},
|
||
|
||
// 系统信息(从缓存读取,避免重复调用)
|
||
systemInfo: uni.getStorageSync('systemInfo') || {
|
||
statusBarHeight: 0,
|
||
windowHeight: 0,
|
||
windowWidth: 0,
|
||
platform: ''
|
||
},
|
||
|
||
// 账单列表
|
||
billList: storage.get('bill_list') || [],
|
||
|
||
});
|
||
|
||
// 定义操作方法
|
||
export const useStore = () => {
|
||
// 用户相关操作
|
||
const setUserInfo = (userInfo) => {
|
||
store.userInfo = userInfo;
|
||
};
|
||
|
||
const clearUserInfo = () => {
|
||
store.userInfo = null;
|
||
};
|
||
|
||
// 设置相关操作
|
||
const updateSettings = (settings) => {
|
||
store.settings = { ...store.settings, ...settings };
|
||
};
|
||
|
||
// 账单相关操作
|
||
const addBill = (bill) => {
|
||
store.billList.unshift(bill);
|
||
return bill;
|
||
};
|
||
|
||
const updateBill = (id, updates) => {
|
||
const index = store.billList.findIndex(bill => bill.id === id);
|
||
if (index !== -1) {
|
||
store.billList[index] = { ...store.billList[index], ...updates };
|
||
return store.billList[index];
|
||
}
|
||
return null;
|
||
};
|
||
|
||
const deleteBill = (id) => {
|
||
const index = store.billList.findIndex(bill => bill.id === id);
|
||
if (index !== -1) {
|
||
store.billList.splice(index, 1);
|
||
return true;
|
||
}
|
||
return false;
|
||
};
|
||
|
||
const getBillList = () => {
|
||
return store.billList
|
||
}
|
||
|
||
// 手动保存账单列表(替代自动监听)
|
||
const saveBillList = debounce(() => {
|
||
storage.set('bill_list', store.billList)
|
||
}, 500)
|
||
|
||
// 优化后的监听:使用防抖减少存储频率
|
||
const debouncedSaveSettings = debounce((newValue) => {
|
||
storage.set('settings', newValue)
|
||
}, 500)
|
||
|
||
watch(
|
||
() => store.userInfo,
|
||
(newValue) => storage.set('userInfo', newValue),
|
||
{ deep: true }
|
||
);
|
||
|
||
watch(
|
||
() => store.settings,
|
||
(newValue) => debouncedSaveSettings(newValue),
|
||
{ deep: true }
|
||
);
|
||
|
||
// 移除billList的自动监听,改为手动调用saveBillList
|
||
|
||
// 获取系统信息(从缓存读取)
|
||
const getSystemInfo = () => {
|
||
const cachedInfo = uni.getStorageSync('systemInfo')
|
||
if (cachedInfo) {
|
||
store.systemInfo = cachedInfo
|
||
}
|
||
};
|
||
|
||
return {
|
||
store,
|
||
setUserInfo,
|
||
clearUserInfo,
|
||
updateSettings,
|
||
addBill,
|
||
updateBill,
|
||
deleteBill,
|
||
getBillList,
|
||
saveBillList,
|
||
getSystemInfo
|
||
};
|
||
};
|