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)
}
}