从微信小程序到鸿蒙JS开发-storage缓存&自动登录
想了解更多内容,从微程序请访问:
和华为官方合作共建的到鸿登录鸿蒙技术社区
https://harmonyos.51cto.com
在应用开发时,我们常需要将一些数据缓存到本地,缓存以提升用户体验。自动比如在一个电商的从微程序app中,如果希望用户登录成功后,到鸿登录下次打开app可以自动登录,缓存就需要将用户信息存储到缓存中。自动
鸿蒙JS开发模式提供了操作数据缓存的从微程序API,首先需导入storage模块。到鸿登录
import storage from @system.storage;添加缓存的缓存API为storage.set( ),指定key和value,自动在用户登录成功后将用户名和密码缓存到本地:
// 登录 login() { fetch.fetch({ url: this.url + "/user/login?从微程序phone=" + this.phone + "&pwd=" + this.pwd, responseType: "json", success: res => { let data = JSON.parse(res.data); console.info(JSON.stringify(data)); if (0 != data.code) { prompt.showToast({ message: data.msg, duration: 3000 }) } else { let userInfo = data.data; ...... // 写入缓存 storage.set({ key: "userPhone", value: userInfo.mobile }); storage.set({ key: "userPwd", value: userInfo.password }) } } }) },注意,鸿蒙JS的到鸿登录数据缓存API是以key:value进行存取的,value只能为string类型。缓存如存储其他类型,高防服务器并不会失败而进入fail回调,但在使用get( )的时候会无法取到对应value的。
在进入app时,便可调用storage.get( )取出缓存中的用户信息,通过给定key,在success回调中会返回对应的value。取到用户信息后并调用登录方法实现自动登录功能。
onShow() { // 从其他页面跳转回来,清除页面栈 router.clear(); // 从缓存取用户信息,自动登录 storage.get({ key: "userPhone", success: data => { if (data) { this.phone = data; storage.get({ key: "userPwd", success: data => { if (data) { this.pwd = data; this.login(); } } }) } } }) // 查询购物车数量 if (this.userInfo && this.userInfo.id) { this.countCarts(); } },效果如下:
删除缓存中数据的API为storage.delete( ),指定key即可删除对应数据。此方法在IDE中无提示(猜测是和delete关键词重复了),但经实验是可以正常使用的。
在用户退出登录后,企商汇应清除缓存中的用户信息。对应方法如下:
// 退出登录 exitLogin() { prompt.showDialog({ title: "提示", message: "确认退出登录吗?", buttons: [ { text: "确定", color: "#E20A0B" }, { text: "取消", color: "#666666" } ], success: res => { if (res.index == 0) { ...... // 删除缓存中用户信息 storage.delete({ key: "userPhone" }); storage.delete({ key: "userPwd" }); this.userInfo = null; } } }) }退出登录过后再次进入app,就不会自动登录了:
此外还有storage.clear( )方法用于清空所有的数据缓存。
微信小程序提供了类似的操作数据缓存的方法,分为同步方法和异步方法,且数据的value可为任何能够通过JSON.stringify序列化的对象。因此在从微信小程序切换到鸿蒙JS开发时,在数据缓存这里踩了坑。鸿蒙storage的value只能为string,但其提供了文件存储,拥有更强大的数据存储能力。
想了解更多内容,请访问:
和华为官方合作共建的鸿蒙技术社区
https://harmonyos.51cto.com