微信小程序基础api封装三部曲(二)

2. 微信小程序 本地存储 storage.js 封装
// storage.js
/**
 * @description 存储数据  同步版本
 * @param {string} key 本地缓存中指定的 key
 * @param {Object} data 需要存储的内容。只支持原生类型、Date、及能够通过JSON.stringify序列化的对象。
 */
export const setStorage = (key, data) => {
  try {
    wx.setStorageSync(key, data)
  } catch (error) {
    console.log(`存储指定 ${key} 数据发生异常 `, error)
  }
}

/**
 * @description 获取本地数据 
 * @param {*} key 本地缓存中指定的 key
 */
export const getStorage = (key) => {
  try {
    const value = wx.getStorageSync(key)
    if (value) {
      // Do something with return value
      return value
    }
  } catch (error) {
    console.log(`读取指定 ${key} 数据发生异常 `, error)
  }
}


/**
 * @description 移除本地数据 
 * @param {*} key 本地缓存中指定的 key
 */
export const removeStorage = (key) => {
  try {
    wx.removeStorageSync(key)
  } catch (error) {
    console.log(`移除指定 ${key} 数据发生异常 `, error)
  }
}
/**
 * @description 移除本地所有数据 
 */
export const clearStorage = () => {
  try {
    wx.clearStorageSync()
  } catch (error) {
    console.log(`清除 数据发生异常 `, error)
  }
}

/**
 * @description 将数据存储在本地缓存中 指定的 key 中。异步api
 * 会覆盖掉原来该 key 对应的内容。
 * 除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。
 * @param {string} key 
 * @param {Object} data  需要存储的内容。只支持原生类型、Date、及能够通过JSON.stringify序列化的对象。
 */
export const asyncSetStorage = (key, data)=>{
  return new Promise((reslove)=>{
    wx.setStorage({
      key,
      data,
      complete(res){
        reslove(res)
      }
    })
  })
}

/**
 * @description 从本地缓存中异步获取指定 key 的内容  
 * @param {*} key 
 */
export const asyncGetStorage = (key)=>{

  return new Promise((reslove)=>{
    wx.getStorage({
      key,
      complete(res){
        reslove(res)
      }
    })
  })
}

/**
 * @description 从本地缓存中异步移除指定 key 的内容  
 * @param {*} key 
 */
export const asyncRemoveStorage = (key)=>{

  return new Promise((reslove)=>{
    wx.removeStorage({
      key,
      complete(res){
        reslove(res)
      }
    })
  })
}


/**
 *  @description 异步移除 本地缓存数据
 */
export const asyncClearStorage = ()=>{
  return new Promise((reslove)=>{
    wx.clearStorage({
      complete(res){
        reslove(res)
      }
    })
  })
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值