微信小程序开发,StorageSync数据存储和封装

1. 官方文档指南:

**同步的4个方法**

  1. setStorageSync: https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorageSync.html

功能描述
将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。

参数
string key
本地缓存中指定的 key

any data
需要存储的内容。只支持原生类型、Date、及能够通过JSON.stringify序列化的对象。

注意

storage 应只用来进行数据的持久化存储,不应用于运行时的数据传递或全局状态管理。启动过程中过多的同步读写存储,会显著影响启动耗时。

示例代码

try {
  wx.setStorageSync('name', '张三')
} catch (e) { }
  1. getStorageSynchttps://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageSync.html

功能描述
从本地缓存中同步获取指定 key 的内容。

参数
string key
本地缓存中指定的 key

返回值
any
key对应的内容

注意

storage 应只用来进行数据的持久化存储,不应用于运行时的数据传递或全局状态管理。启动过程中过多的同步读写存储,会显著影响启动耗时。

示例代码

try {
  var value = wx.getStorageSync('name')
  if (value) {
    // Do something with return value
  }
} catch (e) {
  // Do something when catch error
}
  1. removeStorageSynchttps://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.removeStorageSync.html

功能描述
从本地移除指定 key 的数据

参数
string key
本地缓存中指定的 key

示例代码

try {
  wx.removeStorageSync('name')
} catch (e) {
  // Do something when catch error
}
  1. clearStorageSynchttps://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.clearStorageSync.html

功能描述
从本地移除,清空全部的数据

示例代码

try {
  wx.clearStorageSync()
} catch(e) {
  // Do something when catch error
}

**异步的4个方法**

  1. setStoragehttps://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.setStorage.html

功能描述
将数据存储在本地缓存中指定的 key 中。会覆盖掉原来该 key 对应的内容。除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。

参数
Object object

属性类型默认值必填说明
keystring本地缓存中指定的 key
dataany需要存储的内容。只支持原生类型、Date及能够通过JSON.stringify序列化的对象。
encryptBooleanfalse是否开启加密存储。只有异步的setStorage接口支持开启加密存储。开启后,将会对data使用AES128加密,接口调用耗时将会增加。若开启加密存储,setStorage和getStorage后的数据比原始数据膨胀1.4倍,因此开启encrypt的情况,单个key允许存储的最大数据长度为0.7MB,所有数据存储上限为7.1MB
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

wx.setStorage({
  key:"key",
  data:"value"
})
  1. getStoragehttps://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorage.html

功能描述
从本地缓存中异步获取指定 key 的内容。

参数
Object object

属性类型默认值必填说明
keystring本地缓存中指定的 key
encryptBooleanfalse是否开启加密存储。只有异步的 getStorage 接口支持开启加密存储。开启后,将会对 data 使用 AES128 解密,接口调用耗时将会增加。若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

wx.getStorage({
  key: 'key',
  success (res) {
    console.log(res.data)
  }
})
  1. removeStoragehttps://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.removeStorage.html

功能描述
从本地缓存中移除指定 key。

参数
Object object

属性类型默认值必填说明
keystring本地缓存中指定的 key
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

wx.removeStorage({
  key: 'key',
  success (res) {
    console.log(res)
  }
})
  1. clearStoragehttps://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.clearStorage.html

功能描述
清理本地数据缓存。

参数
Object object

属性类型默认值必填说明
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

wx.clearStorage()

2. 封装

  1. 封装的意义:
    在项目开发工程中,我们经常会频繁的使用到一些API。如果每次使用直调调用API的话,会导致代码冗余,很多的代码都在重复使用,所以我们要进行封端

3. 实现步骤

  1. 在项目先新建文件夹取名叫utils 然后在utlis文件夹内新建storageUtils.js文件。目录结构如下图所示:
    在这里插入图片描述
  2. 封装实现过程

storageUtils.js



/**
 * 存储数据
 * @param {*} key   本地缓存中指定的 key
 * @param {*} value  需要缓存的数据
 */
export const setStorage = (key, value) => {
	try {
		wx.setStorageSync(key, value)
	} catch (error) {
		console.error(`存储指定${key}数据发生了异常`, error)
	}
}


/**
 * 从本地读取指定 key 的数据
 * @param {*} key 
 */
export const getStorage = (key) => {
	try {
		const value = wx.getStorageSync(key)
		if (value) {
			return value
		}
	} catch (error) {
		console.error(`读取指定${key}数据发生了异常`, error)
	}
}


/**
 * 从本地移除指定 key 的数据
 * @param {*} key 
 */
export const removeStorage = (key) => {
	try {
		wx.removeStorageSync(key)
	} catch (error) {
		console.error(`移除指定${key}数据发生了异常`, error)
	}
}

/**
 * 从本地移除,清空全部的数据
 */
export const clearStorage = () => {
	try {
		wx.clearStorageSync()
	} catch (error) {
		console.error(`清空,清空数据发生了异常`, error)
	}
}


/**
 * 异步将数据存储到本地
 * @param {*} key      本地缓存中指定的 key
 * @param {*} data     需要缓存的数据
 */
export const asyncSetStorage = (key, data) => {
	return new Promise((resolve) => {
		wx.setStorage({
			key,
			data,
			complete(res) {
				resolve(res)
			}
		})
	})
}

/**
 *异步从本地获取指定 key 的数据
 * @param {*} key    本地缓存中指定的 key
 */
export const asyncGetStorage = (key) => {
	return new Promise((resolve) => {
		wx.getStorage({
			key,
			complete(res) {
				resolve(res)
			}
		})
	})
}

/**
 *异步从本地移除指定 key 的数据
 * @param {*} key    本地缓存中指定的 key
 */
export const asyncRemoveStorage = (key) => {
	return new Promise((resolve) => {
		wx.removeStorage({
			key,
			complete(res) {
				resolve(res)
			}
		})
	})
}


/**
 *异步从本地移除,清空全部的数据
 */
export const asyncClearStorage = () => {
	return new Promise((resolve) => {
		wx.clearStorage({
			complete(res) {
				resolve(res)
			}
		})
	})
}

温馨提示:
上面每个方法中都使用到了export 关键字,因为需要在其他js文件中使用,所以要export 先导出,然后在其它需要使用到的js文件中import导入

4.如何使用?

  1. 使用前先import导入
// app.js
//同步使用
// import {setStorage,getStorage,removeStorage,clearStorage} from './utils/storageUtils'

//异步使用
import { asyncSetStorage, asyncGetStorage, asyncRemoveStorage, asyncClearStorage } from './utils/storageUtils'
App({
	onShow() {

		//同步使用===============================================
		// setStorage('name','王五')
		// setStorage('age',20)

		// const value =	getStorage('name')
		// console.log(value)

		// removeStorage('name')

		// clearStorage()


		//异步使用===============================================

		// 	asyncSetStorage('name', 'wangwu').then((res)=>{
		// 		console.log(res)
		// })

		// asyncSetStorage('age', 20).then((res)=>{
		// 	  console.log(res)
		// })


		// asyncGetStorage('name').then((res=>{
		// 	console.log(res.data)
		// }))


		// asyncRemoveStorage('age').then((res)=>{
		// 	console.log(res)
		// })


		// asyncClearStorage().then((res) => {
		// 	console.log(res)
		// })


	}

})

温馨提示:
import {setStorage,getStorage,removeStorage,clearStorage} from ‘./utils/storageUtils’
注意 from 的路径(./utils/storageUtils)一定要指向正确

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩宇软件开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值