The front-end vue js array object saves the cookie and the back-end gets the implementation

1. Encapsulate and set cookie method

//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'    
},

2. Encapsulate and obtain cookie data

//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 ''
    },

3. Cookie storage array object

When we use cookies to store arrays, we can convert them to JSON strings for storage through **JSON.stringify()**

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)

Fourth, take the cookie array object

After storing the array through the cookie, we can use JSON.parse() to convert the JSON string into an array object when we fetch the array

const lost = JSON.parse(getCookie('LOST'));
console.log('lost',lost)

5. Use encodeURIComponent to store cookies that can be decoded through the backend

After the front-end can normally use the cookie storage array JSON.parse() and JSON.parse() , the back-end cannot get the JSON string with the cookie when it gets the cookie. It is found by querying the data that it contains characters such as commas.

When the cookie is stored in the array object, by using encodeURIComponent() , the ES5 built-in method transcodes, and the backend can get it normally after decoding the 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)

Guess you like

Origin blog.csdn.net/weixin_44982333/article/details/127439937