参考:https://www.jb51.net/article/146656.htm
我分四步来描述:
1.先写出公用方法(全局),含存、取、删的方法
2.存,这个一般都是在登陆界面login.vue时的事情,一般存后台返回的数据
3.取,在需要展示的地方从cookie中获取即可
4.删,就是点击退出登陆等其他类似操作。
全局变量会把?
//登陆信息,供获取cooike给值,来源getCookie()
username:"", //姓名
usernumber:"",//工号
usertype:"",//管理员还是啥,或者天数
一、公用方法,供调用(存,取,删)
方法写在公用地方(全局)-----gongyong.js:
/** 供外部调用的方法 */
//设置cookie --由login调用
setCookie(name,gonghao,type){
var exdate = new Date()
exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * 0.5);
// 字符串拼接cookie
window.document.cookie = 'userName' + '=' + name + ';path=/;expires=' + exdate.toGMTString()
window.document.cookie = 'usernumber' + '=' + gonghao + ';path=/;expires=' + exdate.toGMTString()
window.document.cookie = 'usertype' + '=' + type + ';path=/;expires=' + exdate.toGMTString()
},
getCookie() {//获取cookie中登陆信息
var arr,i,arr1,arr2,arr3,arr4,arr5;
if (document.cookie.length > 0) {
arr = document.cookie.split('; ')
//拆分
arr1 = arr[0].split('=');
this.username=arr1[1]
arr2 = arr[1].split('=');
this.usernumber=arr2[1]
arr3 = arr[2].split('=');
if(arr3[1]=1){
this.usertype="管理员"
}else{
this.usertype="普通员"
}
}
},
//清除cookie
clearCookie() {
this.setCookie("","",-1);//修改2值都为空,天数为负1天就好了
},
二、存,在登陆界面存数据库返回的信息存在cookie中
在登陆界面login中如何取提供个保存?就是登陆的时候,调用公用方法setCookie(),在点击登陆,接收后台返回的验证数据,然后保存过去;
//存登陆信息到cookie中
this.$root.gongyong.setCookie(mylogin.UserName,mylogin.UserAccount,mylogin.UserType);
this.$router.push({name:'home'});//跳转到主界面
三、取,在需要显示的地方取Cookie的内容
然后再要显示的页面显示登陆账户的信息,比如我事再左上角显示 管理员 张三 0000001 这样子
created(){
this.$root.gongyong.getCookie();//获取方法
this.setcookie();//一进来此页面就需要显示登陆内容
},
methods: {
//略,这里事显示登陆或未登录的内容和时间,如:
setcookie(){ //
let username = this.$root.gongyong.username;
let usernumber = this.$root.gongyong.usernumber
let usertype = this.$root.gongyong.usertype
// console.log("当前登陆信息",username,usernumber,usertype);
if(username === null || username ==="" ){
this.$alert('当前未登陆,请先登陆后再操作', '友情提示', {
confirmButtonText: '确定',
callback: action => {
this.$router.push({name:'login'});
}
});
this.titleUser = "未登录,请先登陆。";
}else{
this.allLogin1.username1 = username;
this.allLogin1.usernumber1 = usernumber;
this.allLogin1.usertype1 = usertype;
}
},
noLogin(){//点击用户信息,如果未登录让其登陆
if(this.allLogin1.username1 == "未登录"){
this.$alert('当前未登陆,请先登陆后再操作', '友情提示', {
confirmButtonText: '确定',
callback: action => {
this.$router.push({name:'login'});
}
});
}
},
}
四、删,退出登陆时清空cookie中存的内容
点击退出按钮,执行清空的方法。
logout(){//点击退出登陆登陆按钮
if(confirm("您确定要退出本系统吗?")){
// window.location.href = "@/views/login/Login.vue";
this.$router.push({ name: "login"})
this.$root.gongyong.clearCookie();//删除所有cookie变量
}
},