這次給你們安利的是微信小程序封裝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的名稱判斷,以及是否是異步進行了判斷,