2024-11-18 19:40:44 +08:00
|
|
|
import type { LayoutSettings } from "@/config/layouts"
|
|
|
|
import type { Ref } from "vue"
|
|
|
|
import { layoutSettings } from "@/config/layouts"
|
2024-11-14 17:33:12 +08:00
|
|
|
import { pinia } from "@/store"
|
2023-06-30 13:43:20 +08:00
|
|
|
import { setConfigLayout } from "@/utils/cache/local-storage"
|
2024-11-18 19:40:44 +08:00
|
|
|
import { defineStore } from "pinia"
|
|
|
|
import { ref, watch } from "vue"
|
2022-04-21 18:20:39 +08:00
|
|
|
|
2023-05-26 13:04:12 +08:00
|
|
|
type SettingsStore = {
|
|
|
|
// 使用映射类型来遍历 layoutSettings 对象的键
|
2023-06-30 13:43:20 +08:00
|
|
|
[Key in keyof LayoutSettings]: Ref<LayoutSettings[Key]>
|
2023-05-26 13:04:12 +08:00
|
|
|
}
|
2022-04-21 18:20:39 +08:00
|
|
|
|
2023-06-30 13:43:20 +08:00
|
|
|
type SettingsStoreKey = keyof SettingsStore
|
|
|
|
|
2023-05-26 13:04:12 +08:00
|
|
|
export const useSettingsStore = defineStore("settings", () => {
|
|
|
|
/** 状态对象 */
|
|
|
|
const state = {} as SettingsStore
|
|
|
|
// 遍历 layoutSettings 对象的键值对
|
|
|
|
for (const [key, value] of Object.entries(layoutSettings)) {
|
|
|
|
// 使用类型断言来指定 key 的类型,将 value 包装在 ref 函数中,创建一个响应式变量
|
2023-06-30 13:43:20 +08:00
|
|
|
const refValue = ref(value)
|
2024-11-18 19:40:44 +08:00
|
|
|
// @ts-expect-error ignore
|
2023-06-30 13:43:20 +08:00
|
|
|
state[key as SettingsStoreKey] = refValue
|
|
|
|
// 监听每个响应式变量
|
|
|
|
watch(refValue, () => {
|
|
|
|
// 缓存
|
|
|
|
const settings = _getCacheData()
|
|
|
|
setConfigLayout(settings)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
/** 获取要缓存的数据:将 state 对象转化为 settings 对象 */
|
|
|
|
const _getCacheData = () => {
|
|
|
|
const settings = {} as LayoutSettings
|
|
|
|
for (const [key, value] of Object.entries(state)) {
|
2024-11-18 19:40:44 +08:00
|
|
|
// @ts-expect-error ignore
|
2023-06-30 13:43:20 +08:00
|
|
|
settings[key as SettingsStoreKey] = value.value
|
|
|
|
}
|
|
|
|
return settings
|
2022-12-08 18:06:01 +08:00
|
|
|
}
|
2023-05-26 13:04:12 +08:00
|
|
|
|
|
|
|
return state
|
2022-04-21 18:20:39 +08:00
|
|
|
})
|
2024-11-14 17:33:12 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
|
|
|
|
* 在 SSR 应用中可用于在 setup 外使用 store
|
|
|
|
*/
|
2024-11-21 20:41:48 +08:00
|
|
|
export function useSettingsStoreOutside() {
|
2024-11-14 17:33:12 +08:00
|
|
|
return useSettingsStore(pinia)
|
|
|
|
}
|