封装setStorage、getStorage

/**
 * 存储localStorage
 */
export const setStore = (params: any) => {
    const {name, content, type, datetime} = params
    const obj = {
        dataType: typeof (content),
        content: content,
        type: type,
        datetime: new Date().getTime()
    }
    if (type) window.sessionStorage.setItem(name, JSON.stringify(obj))
    else window.localStorage.setItem(name, JSON.stringify(obj))
}
/**
 * 获取localStorage
 */
export const getStore = (params: any) => {
    const {name, type} = params
    let item = window.localStorage.getItem(name)
    if (!item) {
        item = window.sessionStorage.getItem(name)
    }
    if (item) {
        const obj: any = JSON.parse(item)
        let content: any = {}
        if (obj.dataType === 'string') {
            content = obj.content
        } else if (obj.dataType === 'number') {
            content = Number(obj.content)
        } else if (obj.dataType === 'boolean') {
            content = eval(obj.content)
        } else if (obj.dataType === 'object') {
            content = obj.content
        }
        return content
    } else {
        return {}
    }
}
/**
 * 删除localStorage
 */
export const removeStore = (params: any) => {
    const {name} = params
    window.localStorage.removeItem(name)
    window.sessionStorage.removeItem(name)
}

 

posted @ 2022-12-27 09:49  RHCHIK  阅读(68)  评论(0编辑  收藏  举报