雷峰
雷峰
  • 发布:2025-03-06 18:20
  • 更新:2025-03-06 18:20
  • 阅读:17

【经验分享】uniappX中实现类似pinia-plugin-persist-uni的本地数据缓存

分类:uni-app x

主要的实现方法

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 关注 分享

要回复文章请先登录注册