import { reactive, ref, Ref, UnwrapNestedRefs, UnwrapRef, watch } from "vue";
import { Cache } from "./cache";
/**
* Storage缓存ref与reactive,实现监听
*/
class CachedProxy<T extends Object> {
constructor(isRef, cachedKey, value?, isCached?: boolean, isSessionCached?: boolean) {
isCached = isCached ?? true;
isSessionCached = isSessionCached ?? true;
if (isCached) {
this.cachedObj = new Cache(cachedKey, isSessionCached ? 'session' : 'local'); }
const val = this.cachedObj.isEmpty ? (isRef ? value : (value || {})) : this.cachedObj.json
this.proxy = isRef ? ref<T>(val) : reactive<T>(val);
}
/**
* proxy对象
*/
proxy: UnwrapNestedRefs<T> | Ref<UnwrapRef<T>>;
cachedObj: Cache;
/**
* 取消监听事件
*/
watchStop: WatchStopHandle;
/**
* 设置对象监听事件,缓存监听对象
* @param callback 回调函数,有参数(current, prev)
*/
watch(callback?: Function) {
this.watchStop = watch(this.proxy, (current, prev) => {
if (this.cachedObj) {
this.cachedObj.setValue(JSON.stringify(current)); // 缓存
}
callback && callback(current, prev);
},
{ immediate: true });
}
stopWatch() {
this.watchStop && this.watchStop();
}
}
/**
* Storage缓存reactive,实现监听
*/
export class CachedReactive<T extends Object> extends CachedProxy<T> {
constructor(cachedKey, value?, isCached?: boolean) {
super(false, cachedKey, value, isCached);
}
/**
* reactive对象
*/
declare proxy: UnwrapNestedRefs<T>;
}
/**
* Storage缓存ref,实现监听
*/
export class CachedRef<T extends Object> extends CachedProxy<T> {
constructor(cachedKey, value?, isCached?: boolean) {
super(true, cachedKey, value, isCached);
}
/**
* ref对象
*/
declare proxy: Ref<UnwrapRef<T>>;
}