feat: 新增useStorage
This commit is contained in:
@@ -1,17 +0,0 @@
|
||||
/**
|
||||
* 配置浏览器本地存储的方式,可直接存储对象数组。
|
||||
*/
|
||||
|
||||
import WebStorageCache from 'web-storage-cache'
|
||||
|
||||
type CacheType = 'sessionStorage' | 'localStorage'
|
||||
|
||||
export const useCache = (type: CacheType = 'sessionStorage') => {
|
||||
const wsCache: WebStorageCache = new WebStorageCache({
|
||||
storage: type
|
||||
})
|
||||
|
||||
return {
|
||||
wsCache
|
||||
}
|
||||
}
|
||||
31
src/hooks/web/useStorage.ts
Normal file
31
src/hooks/web/useStorage.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { isArray, isObject } from '@/utils/is'
|
||||
|
||||
export const useStorage = (type: 'sessionStorage' | 'localStorage' = 'sessionStorage') => {
|
||||
const setStorage = (key: string, value: any) => {
|
||||
window[type].setItem(key, isArray(value) || isObject(value) ? JSON.stringify(value) : value)
|
||||
}
|
||||
|
||||
const getStorage = (key: string) => {
|
||||
const value = window[type].getItem(key)
|
||||
try {
|
||||
return JSON.parse(value || '')
|
||||
} catch (error) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
const removeStorage = (key: string) => {
|
||||
window[type].removeItem(key)
|
||||
}
|
||||
|
||||
const clear = () => {
|
||||
window[type].clear()
|
||||
}
|
||||
|
||||
return {
|
||||
setStorage,
|
||||
getStorage,
|
||||
removeStorage,
|
||||
clear
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user