參考: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變量
}
},