效果如果所示:
思路:勾选记住密码框,点击登录,账号密码勾选状态保存到cookie,下次登录将账号密码勾选状态从cookie中取出;不勾选时,点击登录清空保存到cookie的值
代码如下:
HTML部分
<template>
<div class="login">
<div class="right">
<div class="title">账号密码登录</div>
<div class="welcome">
<div class="wleft">
<hr style="border: none;border-top:0.005rem solid #666;margin-top:0.09rem" />
</div>
<div class="center">welcome</div>
<div class="wright">
<hr style="border: none;border-top:0.005rem solid #666;margin-top:0.09rem" />
</div>
</div>
<div class="username">
<div class="usernameImg"></div>
<div class="usernameText">
<input type="text" placeholder="请输入账号" v-model="username" />
</div>
</div>
<div class="password">
<div class="passwordImg" >
<img src="../assets/img/password.png" alt />
</div>
<div class="passwordText">
<input placeholder="请输入密码" v-model="password" />
</div>
</div>
<div class="rememberpassword">
<input type="checkbox" v-model="checked" />
<span>记住密码</span>
</div>
<div class="register" @click="loadData">登录</div>
</div>
</div>
</template>
JS部分
data() {
return {
username: "",
password: "",
checked:false
};
},
mounted() {
this.getCookie();
},
methods: {
// 登录
loadData() {
if (Boolean(this.checked) == true) {
console.log(this.checked);
// 将账号密码勾选状态存入cookie中,并设置储存天数
this.setCookie(this.username, this.password,this.checked, 7);
} else {
// 清除cookie值
this.clearCookie();
}
},
//设置cookie
setCookie(c_name, c_pwd,c_che, 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();
window.document.cookie =
"userChe" + "=" + c_che+ ";path=/;expires=" + exdate.toGMTString();
},
//读取cookie
getCookie: function () {
if (document.cookie.length > 0) {
var arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
for (var i = 0; i < arr.length; i++) {
var arr2 = arr[i].split("="); //再次切割
//判断查找相对应的值
console.log(arr2);
if (arr2[0] == "userName") {
this.username = arr2[1]; //保存到保存数据的地方
} else if (arr2[0] == "userPwd") {
this.password = arr2[1];
}else if(arr2[0]=="userChe") {
if(arr2[1]==-1){
this.checked=false
}else {
this.checked=arr2[1];
}
}
}
}
},
//清除cookie
clearCookie: function () {
this.setCookie("", "","", -1); //修改2值都为空,天数为-1就好了
},
},