首页 > 其他分享 >封装setStorage、getStorage

封装setStorage、getStorage

时间:2022-12-27 09:55:07浏览次数:39  
标签:setStorage obj name content window localStorage 封装 getStorage const

/**
 * 存储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)
}

 

标签:setStorage,obj,name,content,window,localStorage,封装,getStorage,const
From: https://www.cnblogs.com/suihung/p/17007408.html

相关文章