一、封装设置cookie方法
//name 字段名 value 字段值 perpetual 有效期
setCookie(name,value,perpetual) {
let exdate = new Date()
exdate.setDate(exdate.getDate() + perpetual) //exdate.setDate(exdate.getDate() + 365)
document.cookie = name + '=' + value + ';expires=' + exdate.toGMTString()
//永久有效
//document.cookie = name + '=' + value + ';expires=' + 'Fri, 31 Dec 9999 23:59:59 GMT'
},
二、封装获取cookie数据
//name 字段名
getCookie (name) {
if (document.cookie.length > 0) {
var start = document.cookie.indexOf(name + '=')
if (start !== -1) {
start = start + name.length + 1
let end = document.cookie.indexOf(';', start)
if (end === -1) end = document.cookie.length
return unescape(document.cookie.substring(start, end))
}
}
return ''
},
三、cookie存数组对象
在我们使用cookie存数组时,可以通过**JSON.stringify()**转换为JSON字符串进行存入
const arr = [
{ id: "a", pid: "", name: "总裁办" },
{ id: "b", pid: "", name: "行政部" },
{ id: "c", pid: "", name: "财务部" },
{ id: "d", pid: "c", name: "财务核算部" },
{ id: "e", pid: "c", name: "税务管理部" },
{ id: "f", pid: "e", name: "税务管理部-分部" },
];
const ex= 7 * 24 * 60 * 60 * 1000
setCookie('LOST',JSON.stringify(arr),ex)
四、cookie取数组对象
通过cookie存数组后,我们取数组时可以通过 JSON.parse() JSON字符串转换为数组对象进行使用
const lost = JSON.parse(getCookie('LOST'));
console.log('lost',lost)
五、使用encodeURIComponent存入可以通过后端获取解码的cookie
取前端可以正常使用cookie存数组 JSON.parse()和JSON.parse() 后,后端在获取cookie获取不到存在cookie的JSON字符串,通过查询资料发现,是因为含有逗号等字符的原因。
在cookie存入数组对象时,通过使用encodeURIComponent() ,ES5内置的方法转编码,后端在获取到cookie后解码就可以正常拿到了。**
const arr = [
{ id: "a", pid: "", name: "总裁办" },
{ id: "b", pid: "", name: "行政部" },
{ id: "c", pid: "", name: "财务部" },
{ id: "d", pid: "c", name: "财务核算部" },
{ id: "e", pid: "c", name: "税务管理部" },
{ id: "f", pid: "e", name: "税务管理部-分部" },
];
const ex= 7 * 24 * 60 * 60 * 1000
setCookie('LOST',encodeURIComponent(JSON.stringify(arr)),ex)