從微信小程序到鴻蒙JS開發-storage緩存&自動登錄
在應用開發時,我們常需要將一些數據緩存到本地,以提升用戶體驗。比如在一個電商的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,但其提供了文件存儲,擁有更強大的數據存儲能力。