vital-form-storage
v0.1.5
Published
表单状态存储库
Downloads
563
Maintainers
Readme
使用原生 JavaScript 实现,旨在支持表单缓存功能,能够无缝集成到 Vue、React 等前端框架中。此方案还具备多标签页同步表单数据的能力,同步逻辑经过防抖处理,并确保在切换或关闭标签页时能立即同步内容。
API
- saveDataToStorage 立即同步数据到 storage
- saveData 防抖处理同步数据到 storage
- loadDataFromStorage 将 storage 的数据同步到表单对象
- clearData 清除当前实例缓存数据
- clearAll 清除所有实例的缓存数据
vue hook 封装
import { onMounted, watch } from "vue";
import FormStorage, { Options } from "vital-form-storage";
/**
*
* @param key 唯一id,用于存储storage的key
* @param formData 表单数据
* @param options 配置项
* @returns FormStorage 实例
*/
export default function useFormStorage(
key: string,
formData: any,
options?: Options
) {
const storage = new FormStorage(key, formData, options);
onMounted(() => {
storage.loadDataFromStorage();
});
watch(
formData,
() => {
storage.saveData();
},
{ deep: true }
);
return storage;
}
react hook 封装
import { useEffect, useMemo } from "react";
import { FormStorage, Options } from "vital-form-storage";
/**
*
* @param id 唯一id
* @param formData 表单数据
* @param setFormData 表单数据的setState函数
* @param option 配置项
*/
export function useReactFormStorage(
id: string,
formData: any,
setFormData: (data: any) => void,
option?: Options
) {
const storage = useMemo(() => new FormStorage(id, formData, option), []);
useEffect(() => {
// 加载数据
setFormData({ ...storage.formData });
const syncFormData = (event: StorageEvent) => {
if (event.key === storage.id && event.newValue) {
setFormData(JSON.parse(event.newValue));
}
};
window.addEventListener("storage", syncFormData);
return () => {
window.removeEventListener("storage", syncFormData);
};
}, []);
useEffect(() => {
storage.formData = formData;
storage.saveData();
}, [formData, storage]);
}