前端vue js 数组对象存cookie 后端获取实现

7 篇文章 1 订阅

一、封装设置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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值