一个简单的存取cookie的小例子
function setCookie(key, val, expires) { //存cookie值
if (typeof val === "object")
val = JSON.stringify(val)
let now1 = new Date()
let checkdate = new Date(now1)
checkdate.setDate(now1.getDate() + expires)
document.cookie = `${key}=${encodeURI(val)};expires=${checkdate}`;
//encodeURI编码
}
function getCookie(key) { //取cookie值
let obj = {}
document.cookie.split("; ").forEach(r => {
let kv = r.split("=")
obj[kv[0]] = decodeURI(kv[1]) //decodeURI解码
})
if (key) {
let res = null //只走try或catch ,finally必走
try {
res = JSON.parse(obj[key])
} catch (error) {
res = obj[key]
} finally {
return res
}
}
return obj
}
// function removeCookie(key) { //清除cookie
// this.setCookie(key, null, -1)
// }
setCookie('key', 'nickname')
setCookie('val', 'Ace')
setCookie("key",null,-1) //这样也可以清除清除cookie
本地存储和临时存储
1.本地存储 永久
localStorage.setItem(‘username’,‘aaa’)
console.log(localStorage.setItem(‘username’,‘aaa’)); //存
// setTimeout(()=>{
// // localStorage.clear()//删
// // localStorage.removeItem('username')//删
// console.log(localStorage.getItem('username'))//取
// },5000)
2.会话存储 临时
sessionStorage.setItem(‘username’,‘aaa’)
console.log(sessionStorage.setItem(‘username’,‘aaa’)); //存
// setTimeout(()=>{
// // sessionStorage.clear()//删
// // sessionStorage.removeItem('username')//删
// console.log(sessionStorage.getItem('username'))//取
// },5000)