• 微信小程序封装storage(含错误处理)


    这次给你们安利的是微信小程序封装storage,先说下微信官方的

           wx.getStorage({
                  key:"",
                  success: function (res) {
                    
                  },
                  fail(error){
                    
                  }
                })

    官方的方法用起来很麻烦,和我们之前习惯用localStorage.getItem看这个就很别扭,你也一样对吧,别问我怎么知道的  你来这文章的时候你肯定就是不习惯官方的,没关系,我给你封装好了。

    第一步、根目录新建utils目录,目录内新建一个utils.js的文件

    第二步、复制下方代码到utils.js文件

    class Utils  {
      constructor() {
        super()
        this.storage = {
          /**
           * @description 读取本地存储,
           * @param { string } 要读取的key
           * @param {boolean} 是否是同步
           * @todo 赌气本地存储,判断key只能是string且非纯空格 如果不是将报错,
           */
          Get: function (key, isSync = false) {
            if (typeof key != "string") {
              throw new Error("key is typeof string at Utils.storage.Get");
              return false;
            }
            if (key.Trim() == "") {
              throw new Error("key is not null at Utils.storage.Get");
              return false;
            }
            return new Promise((resolve, reject) => {
              if (isSync) {
                let result = wx.getStorageSync(key.Trim());
                if(result != ""){
                  resolve(result);
                }else{
                  reject("getStorage:fail data not found");
                }
              } else {
                wx.getStorage({
                  key:key.Trim(),
                  success: function (res) {
                    let result = res.data;
                      resolve(result)
                  },
                  fail(error){
                    reject(error.errMsg);
                  }
                })
              }
            })
          },
          /**
           * @description 设置本地存储,
           * @param { string } 存储的key
           * @param { * } 存储的内容
           * @param {boolean} 是否是同步
           * @todo 设置本地存储,判断key只能是string且非纯空格 如果不是将报错,
           */
          Set: function (key, data, isSync = false) {
            if (typeof key != "string") {
              throw new Error("key is typeof string at Utils.storage.Set");
              return false;
            }
            if (key.Trim() == "") {
              throw new Error("key is not null at Utils.storage.Set");
              return false;
            }
            return new Promise((resolve, reject) => {
              if (isSync) {
                wx.setStorageSync(key.Trim(), data)
                resolve({
                  errMsg: "storage okey",
                });
              } else {
                wx.setStorage({
                  key:key.Trim(),
                  data,
                  success: function (res) {
                    resolve({
                      errMsg: "storage okey",
                    })
                  },
                })
              }
            })
          },
          /**
           * @description 清理本地存储,
           * @param { string } 存储的key(为空将清空所有)
           * @param {boolean} 是否是同步
           * @todo 清理本地存储,如果key为空则清空所有,如果key不为空则清空指定的key
           */
          rm: function (key = "", isSync = false) {
            if (typeof key != "string") {
              throw new Error("key is typeof string at Utils.storage.rm");
              return false;
            }
            return new Promise((resolve, reject) => {
              if (key == "") {
                if (isSync) {
                  wx.clearStorage({
                    success() {
                      resolve({
                        errMsg: "clearStorage is okey"
                      })
                    }
                  })
                } else {
                  wx.clearStorageSync();
                  resolve({
                    errMsg: "clearStorage is okey"
                  })
                }
              } else {
                if (!isSync) {
                  wx.removeStorage({
                    key:key.Trim(),
                    success() {
                      resolve({
                        errMsg: "clearStorage is okey"
                      })
                    }
                  })
                } else {
                  wx.removeStorage(key.Trim());
                  resolve({
                    errMsg: "clearStorage is okey"
                  })
                }
              }
            })
          }
        }
      }
    }
    /**
     * @public
     * @author jinzhenzong
     * @description 为string新增方法,trim为string去掉两端空格
     */
    String.prototype.Trim = function () {
      return this.replace(/(^s*)|(s*$)/g, "");
    }
    export {
      Utils
    }

    第三步、使用

    目标页面引入

    import { Utils } from "../../utils/util.js"
    data里面新建一个utils的变量,如下图所示,onload对这歌变量初始化

    在需要的地方这么用:

    this.data.utils.storage.Get("userser").then(res => {
          console.log(res);
         
        }).catch(error => {
        })

    需要设置请用.Set需要异步的话请在第二个参数设为true,该文件是promise风格,兼容了对key的名称判断,以及是否是异步进行了判断,

  • 相关阅读:
    typora 页内跳转
    shell脚本搭建redis集群
    Html
    python json模块
    jenkins 问题合集
    day05 每日一行
    day04 每次一行
    day03 每日一行
    day02
    day02 每日一行
  • 原文地址:https://www.cnblogs.com/jinzhenzong/p/9773238.html
Copyright © 2020-2023  润新知