Skip to content

useStorageMap

useStorageMap(key): Object

使用本地存储的 Map

参数

NameTypeDescription
keystring | string[]唯一的 key

返回值

Object

相关操作方法

NameType
clear() => void
delete(id: string | string[]) => void
get(id: string | string[]) => boolean
has(id: string | string[]) => boolean
set(id: string | string[], options?: { expiredAt: undefined | number ; expiresIn: undefined | number ; value: any }) => void
valuenull

clear: () => void

清空 Map 并清除本地存储

示例

ts
const xxxStorageMap = useStorageMap('key')

xxxStorageMap.clear()

delete: (id: string | string[]) => void

从 Map 中删除元素,并保存到本地存储

示例

ts
const xxxStorageMap = useStorageMap('key')

xxxStorageMap.delete('id')

get: (id: string | string[]) => boolean

从 Map 中获取元素

示例

ts
const xxxStorageMap = useStorageMap('key')

xxxStorageMap.get('id')

has: (id: string | string[]) => boolean

检查元素是否存在于 Map 中

示例

ts
const xxxStorageMap = useStorageMap('key')

xxxStorageMap.has('id')

set: (id: string | string[], options?: { expiredAt: undefined | number ; expiresIn: undefined | number ; value: any }) => void

将元素添加到存储的 Map 中,并保存到本地存储 注意:当 expiredAt 和 expiresIn 同时设置,expiredAt 优先级更高

示例

ts
const xxxStorageMap = useStorageMap('key')

xxxStorageMap.set('id', {
  value: 'some_value',
  expiresIn: 60,
})

value: null

该 value 对象为当前 Map 存储的值,只读,但响应式可被监听


示例

ts
// useStorageMap 内部会将数组合并成字符串作为每条记录的 key
const STORAGE_KEY = {
  VIEW_AREA_WELCOME: 'view_area_welcome',
}
const area = ['广东', '广州', '海珠']
const welcomeStorageMap = useStorageMap(STORAGE_KEY.VIEW_AREA_WELCOME)

// 当执行 set 的时候,该 computed 也能重新计算
const showMessage = computed(() => !welcomeStorageMap.get(area))

const onCloseMessage = () => {
  welcomeStorageMap.set(area, {
    expiredAt: dayjs().add(1, 'day').unix(),
  })
}

源码

use-storage-map.js