主要的实现方法
export function defineStore<T>(name : string, obj : T) : T {
let storage = uni.getStorageSync(name);
if (storage instanceof UTSJSONObject) {
let data = JSON.parse<T>(JSON.stringify(storage));
if (data != null) {
let newVal = data as T;
obj = reactive(newVal);
}
}
watch(obj as any, () => {
uni.setStorage({
key: name,
data: obj as any
});
}, {
deep: true
})
return obj;
}
调用示例:
type UserStore = {
initReady : boolean;
userInfo: UTSJSONObject;
}
export const app = defineStore("app", reactive<UserStore>({
initReady: false,
userInfo:{}
}))
页面中app.xxx就是响应式,参考官方文档:https://doc.dcloud.net.cn/uni-app-x/tutorial/store.html#%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F%E4%B8%8E%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86
如果没有这种处理,app每次启动的时候,状态都会重置。加了后数据就能本地持久化了。
0 个评论
要回复文章请先登录或注册