vue项目登陆设置cookie、获取cookie 、删除 cookie

1.定义方法到存储全局变量 的 global.js 文件中
设置 domain 值 const domain= ’ 域名 ‘; 设置该cookie只对 改域名生效

设置cookie

//设置cookie,增加到vue实例方便全局调用 
function setCookie (c_name, value, expiredays) { 
var exdate = new Date(); 
exdate.setDate(exdate.getDate() + expiredays); 
let path=’/’; 
// document.cookie = c_name + “=” + encodeURIComponent(value)+’;expires’ +exdate.toGMTString()+’;path=’+path+’;domain=’+domain; 设置成功后不在登陆 
document.cookie = c_name + “=” + encodeURIComponent(value)+’;expires’ + exdate.toGMTString()+’;path=’+path; 
};

获取cookie

//获取cookie、 
function getCookie(cname) { 
var name = cname + “=”; 
var ca = document.cookie.split(‘;’); 
for (var i = 0; i < ca.length; i++) { 
var c = ca[i]; 
while (c.charAt(0) == ’ ‘) c = c.substring(1); 
if (c.indexOf(name) != -1) return c.substring(name.length, c.length); 
} 
return “”; 
}

删除cookie

//删除cookie
 function 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();
};

将 global.js 文件导出

2将global文件 在main.js文件中引入 并注入到 vue实例上

import global from ‘./global’ 
Vue.prototype.$global=global; //全局变量

3.调用方式 ‘SYB_TX[dl_quanxian]’ 为cookie存储名
_this.global.setCookie(‘SYB_TX[dl_quanxian]’, CookieData.dl_quanxian);
_this.global.getCookie(‘SYB_TX[dl_quanxian]’);
_this.global. delCookie(‘SYB_TX[dl_quanxian]’)

猜你喜欢

转载自blog.csdn.net/weixin_42220039/article/details/82220312