vue.js設置、獲取、刪除cookie


 

 項目需要前端獲取后台返回的cookie,並以此作判斷。我是在main.js入口文件下使用的

具體代碼:

new Vue({
el: '#app',
router,
template: '<App/>',
components: { App },
methods:{

//讀取cookie,需要注意的是cookie是不能存中文的,如果需要存中文,解決方法是后端先進行編碼encode(),前端取出來之后用decodeURI('string')解碼。(安卓可以取中文cookie,IOS不行)
    getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg)){
        return true;
       // return (arr[2]);
      }else{
      return false
     }
},

//設置cookie   name為cookie的名字,value是值,expiredays為過期時間(天數)
   setCookie (name, value, expiredays) {
     var exdate = new Date();
     exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
   },

 //刪除cookie

   delCookie (name) {
      var exp = new Date();
      exp.setTime(exp.getTime() - 1);
      var cval = getCookie(name);
     if (cval != null)
     document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
   }

},
created(){
   this.setCookie('openId',123,2)
   if (this.getCookie('openId')) {
   console.log('has cookie')

  this.delCookie ('openId')
   }else{
   console.log('has not cookie')
   }
}
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM