LocalStorage
API_LEVEL
3.0开始支持,API 兼容性请参考 API_LEVEL。
本地存储的键值对,数据在小程序卸载过后清除。实例会将读取的数据保留在内存中,适合连续读写以减少重复文件读取。
信息
权限代码: device:os.local_storage
构造函数
创建本地存储实例。默认使用小程序的本地存储文件,也可以指定自定义文件路径
constructor(storagePath?: string)
方法
setItem
保存数据
setItem(key: string, value: any): void
getItem
读取数据,指定默认值 defaultValue 后,如果没有获取到指定 key 上的值,返回 defaultValue
getItem<T = any>(key: string, defaultValue?: T): T | undefined
removeItem
删除所指定 key 的数据
removeItem(key: string): boolean
clear
清空 localStorage 中所有数据
clear(): void
代码示例
import { LocalStorage } from '@zos/storage'
const localStorage = new LocalStorage()
localStorage.setItem('test', 'test value')
const val = localStorage.getItem('test')
const defaultValue = localStorage.getItem('none_key', 'defaultValue')
localStorage.removeItem('test')
localStorage.clear()