const cookie = (function () {
/*
@params {String} key cookie的名称
@params {String} value cookie的值
@params {Number} time cookie的过期时间 秒
*/
// 设置cookie
function setItem(key, value, time) {
let expires = null
// 判断传过来time没有,设置cookie过期时间,若没有为会话级
if (time) {
let d = new Date()
let times = d.getTime() + time * 1000
d.setTime(times)
expires = d.toUTCString()
}
document.cookie = `${key}=${value};expires=` + expires
}
// 获取单个cookie的值
function getItem(key) {
let obj = {}
let arr = document.cookie.split('; ')
arr.forEach(it => {
let res = it.split('=')
obj[res[0]] = res[1]
})
return obj[key]
}
// 删除单个cookie
function removeItem(key) {
setItem(key, 0, -1)
}
// 清除所有的cookie
function clear() {
let obj = {}
let arr = document.cookie.split('; ')
arr.forEach(it => {
let res = it.split('=')
removeItem(res[0])
})
}
let cookie = {
setItem,
getItem,
removeItem,
clear
}
return cookie
})()