フロントエンドの vue js 配列オブジェクトは Cookie とバックエンドの取得実装を保存します。

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

2. 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 ''
    },

3. Cookie ストレージ配列オブジェクト

Cookie を使用して配列を保存する場合、**JSON.stringify()** を通じて保存するために Cookie を 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)

4 番目に、Cookie 配列オブジェクトを取得します。

Cookie を介して配列を保存した後、配列を取得するときにJSON.parse()を使用してJSON 文字列を配列オブジェクトに変換できます。

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

5. encodeURIComponent を使用して、バックエンドを通じてデコードできる Cookie を保存します。

フロントエンドが通常 Cookie ストレージ配列JSON.parse()およびJSON.parse()を使用できるようになった後、バックエンドは Cookie を取得するときに Cookie を含む JSON 文字列を取得できません。カンマなどの文字が含まれています。

encodeURIComponent()を使用して Cookie が配列オブジェクトに格納されている場合、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)

おすすめ

転載: blog.csdn.net/weixin_44982333/article/details/127439937