Vue项目实现记住密码功能
记住密码一般是记录在cookie中,设置一个过期时间,在过期时间之内用户的用户名和密码都保存在cookie中。
首先编写存入/取出信息cookie中的方法
// 设置cookie
mounted() {
this.getCookie();
},
methods: {
setCookie(cname,cpwd,cdays) {
//获取当前时间
var curDate = new Date();
//设置7天过期时间
curDate.setTime(curDate.getTime() + 24*60*60*1000*curDate*cdays);
//字符串拼接cookie
window.document.cookie = "username"+"="+cname+";path=/;expires=" + curDate.toLocaleString();
window.document.cookie = "password"+"="+pwd+";path=/;expires=" + curDate.toLocaleString();
window.document.cookie = "isChecked" + "=" + this.isChecked + ";"
},
//获取cookie
getCookie() {
if(document.cookie.length > 0) {
var arr = document.cookie.split("; ");
for(var i=0;i<arr.length;i++) {
var arr2 = arr[i].split("=");
if(arr2[0] == "username") {
this.formInline.user = arr2[1];
} else if(arr2[0] == "password") {
this.formInline.password = arr2[1];
}else if(arr2[0] == 'isChecked') {
this.isChecked = Boolean(arr2[1]);
}
}
}
//清除cookie
clearCookie() {
this.setCookie("","",-1);
}
}
}