Files
mini-programs/src/store/global.ts
张成 5fdee20d45 1
2025-09-10 21:43:36 +08:00

74 lines
1.7 KiB
TypeScript

import { create } from "zustand";
import { getNavbarHeight } from "@/utils/getNavbarHeight";
import { getCurrentLocation } from "@/utils/locationUtils";
interface GlobalState {
location: Record<string, any>;
getLocationLoading: boolean;
getLocationText: string;
statusNavbarHeightInfo: {
statusBarHeight: number;
navbarHeight: number;
totalHeight: number;
};
}
interface GlobalActions {
updateState: (payload: Record<string, any>) => void;
getNavbarHeightInfo: () => void;
getCurrentLocationInfo: () => any;
}
// 完整的 Store 类型
type GlobalStore = GlobalState & GlobalActions;
// 创建 store
export const useGlobalStore = create<GlobalStore>()((set, get) => ({
// 位置信息
location: {},
// 正在获取位置信息
getLocationLoading: true,
// 获取位置信息文本
getLocationText: "定位中...",
// 状态栏和导航栏高度信息
statusNavbarHeightInfo: {
statusBarHeight: 0,
navbarHeight: 0,
totalHeight: 0,
},
// 获取导航栏高度信息
getNavbarHeightInfo: () => {
const { statusBarHeight, navbarHeight } = getNavbarHeight();
set({
statusNavbarHeightInfo: {
statusBarHeight,
navbarHeight,
totalHeight: statusBarHeight + navbarHeight,
},
});
},
// 获取位置信息
getCurrentLocationInfo: async () => {
const res = await getCurrentLocation()
set({
getLocationLoading: false,
location: res || {},
});
return res;
},
// 更新store数据
updateState: (payload: Record<string, any>) => {
const state = get();
set({
...state,
...(payload || {}),
});
},
}));
// 导出便捷的 hooks
export const useGlobalState = () => useGlobalStore((state) => state);