实现:
- 记住密码 - 用户名密码自动填充 + 勾选单选框
- 未选中记住密码 - 初次进入 - 聚焦用户名输入框
- 未选择记住密码 - 重复进入 - 聚焦密码输入框(显示上次登录的用户名)
HTML
<el-checkbox v-model="checked" style="color:#a0a0a0;margin-top:-10px;">记住密码</el-checkbox>
data
loginForm: { username: '', password: '' }, // 用户名密码
checked:false //是否选中记住密码
mounted
mounted() {
// 读取cookie
// 初次登录 聚焦用户名输入框
// 未记住密码 聚焦密码输入框
// 记住密码 选中单选框
this.getCookie();
if (this.loginForm.username === '') {
this.$refs.username.focus()
} else if (this.loginForm.password === '') {
this.$refs.password.focus()
} else if (this.loginForm.username != '' && this.loginForm.password != '') {
this.checked = true
}
},
method
// 点击登录
handleLogin() {
if (this.checked == true) {
//传入账号名,密码,和保存天数3个参数
this.setCookie(this.loginForm.username, this.loginForm.password, 7);
} else {
//清空Cookie
this.clearCookie();
}
this.$refs.loginForm.validate(valid => {
if (valid) {
console.log(valid)
this.loading = true
this.$store
.dispatch('user/login', this.loginForm)
.then(() => {
//传入账号名和保存天数2个参数
this.setCookieUserName(this.loginForm.username, 7);
})
.catch(() => {
this.loading = false
})
} 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 =
"userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
},
// 设置cookie user
setCookieUserName(c_name, 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();
},
// 获取cookie
getCookie: function() {
if (document.cookie.length > 0) {
console.log(document.cookie)
var arr = document.cookie.split("; ");
for (var i = 0; i < arr.length; i++) {
var arr2 = arr[i].split("=");
if (arr2[0] == "userName") {
this.loginForm.username = arr2[1];
} else if (arr2[0] == "userPwd") {
this.loginForm.password = arr2[1];
}
}
}
},
//清除cookie
clearCookie: function() {
this.setCookie("", "", -1); //天数为-1 值为空
}