Vue 获取登录用户名

本来是打算登录的时候把用户名传过去,试了几次都没成功,然后改成用cookie保存用户名,然后在读取就行了,

登录时候设置cookie

setCookie(c_name,c_pwd,exdays) {
var exdate=new Date();
exdate.setTime(exdate.getTime() + 24*60*60*1000*exdays);
window.document.cookie="userName"+ "=" +c_name+";path=/;expires="+exdate.toGMTString();
window.document.cookie="userPwd"+"="+c_pwd+";path=/;expires="+exdate.toGMTString();
}

获取cookoe

getCookie:function () {
if (document.cookie.length>0) {
var arr=document.cookie.split('; ');
if(arr[1].indexOf("userPwd")!=-1){
let arr2=arr[1].substring(arr[1].indexOf("=")+1);
return arr2;
}
}
}

设置用户名的时候得写在钩子函数里面,不然模板不会被渲染。

退出的时候可以删除cookie

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

这样就可以做一个登录和退出的操作了

猜你喜欢

转载自www.cnblogs.com/liubu/p/9023245.html