init: 迁移本地前端代码(Gitea 仓库重建后重新初始化)
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import { ref, watch, type Ref } from "vue";
|
||||
|
||||
/**
|
||||
* 将任意响应式数据与 sessionStorage 双向绑定
|
||||
* @param key sessionStorage 的 key
|
||||
* @param def 默认值(当 sessionStorage 没有时)
|
||||
* @param reviver 可选:解析时用 JSON.parse 的第二个参数
|
||||
* @returns Ref<T>
|
||||
*/
|
||||
export function useSessionStorage<T>(
|
||||
key: string,
|
||||
def: T,
|
||||
reviver?: (this: any, key: string, value: any) => any,
|
||||
): Ref<T> {
|
||||
/* ---------- 初始化 ---------- */
|
||||
const raw = sessionStorage.getItem(key);
|
||||
let init: T = def;
|
||||
if (raw) {
|
||||
try {
|
||||
init = JSON.parse(raw, reviver);
|
||||
} catch {
|
||||
/* 解析失败回退默认值 */
|
||||
}
|
||||
}
|
||||
const state = ref<T>(init) as Ref<T>;
|
||||
|
||||
/* ---------- 变化时落盘 ---------- */
|
||||
watch(
|
||||
state,
|
||||
newVal => {
|
||||
sessionStorage.setItem(key, JSON.stringify(newVal));
|
||||
},
|
||||
{ deep: true, flush: "post" },
|
||||
);
|
||||
|
||||
return state;
|
||||
}
|
||||
Reference in New Issue
Block a user