vue在登录时使用cookies记住密码
submitForm(formName) {
var FormData = this.FormData;
const _this = this;
var obj = {
loginId: FormData.username,
password: FormData.password,
verify: FormData.verify,
sign: this.sign,
authsign:FormData.authsign
};
// console.log(obj);
this.$refs[formName].validate(valid => {
if (valid) {
this.$index.API_LOGIN(obj).then(res => {
// console.log(res);
if (res.errcode == 0) {
this.FormData.authsign = res.data.authsign;
localStorage.setItem("avatarImg", res.data.avatar);
localStorage.setItem("mobile", res.data.mobile);
localStorage.setItem("nickname", res.data.nickname);
localStorage.setItem("token", res.token);
this.$router.replace({ name: "FirstPaper" }); //登陆成功跳转到首页
//判断复选框是否被勾选 勾选则调用配置cookie方法
if (_this.checked == true) {
//传入账号名,密码,和保存天数3个参数
_this.setCookie(
_this.FormData.username,
_this.FormData.authsign,
7
);
} else {
_this.clearCookie(); //清空Cookie
}
localStorage.setItem("checked", this.checked);
}
});
} else {
console.log("error submit!!");
return false;
}
});
},
//设置cookie
setCookie(c_name, c_pwd, exdays) {
var exdate = new Date(); //获取时间
exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
//字符串拼接cookie
window.document.cookie =
"userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
window.document.cookie =
"authsign" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
},
//读取cookie
getCookie() {
if (document.cookie.length > 0) {
var arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
// console.log(arr);
for (var i = 0; i < arr.length; i++) {
var arr2 = arr[i].split("="); //再次切割
//判断查找相对应的值
if (arr2[0] == "userName") {
this.checked=true;
this.FormData.username = arr2[1]; //保存到保存数据的地方
} else if (arr2[0] == "authsign") {
this.FormData.authsign = arr2[1];
this.FormData.password = arr2[1].substr(0,6);
}
}
}
},
//清除cookie
clearCookie() {
this.setCookie("", "", -1); //修改2值都为空,天数为负1天就好了
},
监听cookie,其中的“checked”为true则表示用户已勾选“记住密码”了。
mounted() {
this.getCookie();
},
created() {
//判断是否记住密码
if (localStorage.getItem("checked") == 'true') {
this.getCookie();
}
},
这里加密则是后台对我登录时输入数据进行加密然后把原先的“password”转换为后台加密返回的“authsign”即可。