js缓存类工具方法

发布时间:2024年01月13日

Cookie

export const getCookie = (k) => {
  const res = RegExp('(^|; )' + encodeURIComponent(k) + '=([^;]*)').exec(document.cookie)
  return res && res[2]
}
export function setCookie(name, value, expriesDays, encode = false) {
  var Days = expriesDays || 10
  var exp = new Date()
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
  const val = encode ? escape(value) : value
  document.cookie = name + '=' + val + ';domain=zhuanzhuan.com;path=/;expires=' + exp.toUTCString()
}

sessionStorage

export function getStorage(key) {
  const content = sessionStorage.getItem(key)
  if (content) {
    try {
      return JSON.parse(content)
    } catch (e) {
      console.log(e)
    }
  }
}

export function setStorage(key, data = {}) {
  try {
    sessionStorage.setItem(key, JSON.stringify(data))
  } catch (e) {
    console.log(e)
  }
}

export function remStorage(key){
	sessionStorage.removeItems(key)
}

localStorage

const prefix = '_XXX_'
export function getStorage(key) {
  const content = localStorage.getItem(`${prefix}${key}`)
  if (content) {
    try {
      const params = JSON.parse(content)
      const expires = params.expires
      // 未设置过期 及 未过期
      if (!expires || (expires && Date.now() <= expires)) {
        return params.data
      }
    } catch (e) {
      console.log(e)
    }
  }
}

export function setStorage(key, data = {}, expires) {
  try {
    const params = { data }
    if (expires) {
      params.expires = expires
    }
    localStorage.setItem(`${prefix}${key}`, JSON.stringify(params))
  } catch (e) {
    console.log(e)
  }
}
文章来源:https://blog.csdn.net/elena_705/article/details/135571408
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。