1.記住密碼勾選,點登錄時,將帳號和密碼保存到cookie,下次登錄自動顯示到表單內 2.不勾選,點登錄時候則清空以前保存到cookie的值,下次登錄須要手動輸入html
大致思路就是經過存/取/刪cookie實現的;每次進入登陸頁,先去讀取cookie,若是瀏覽器的cookie中有帳號信息,就自動填充到登陸框中,存cookie是在登陸成功以後,判斷當前用戶是否勾選了記住密碼,若是勾選了,則把帳號信息存到cookie當中,效果圖如上:vue
<div class="ms-login">
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
<el-form-item prop="username">
<el-input v-model="ruleForm.username" placeholder="用戶名"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" placeholder="密碼" v-model="ruleForm.password" @keyup.enter.native="submitForm('ruleForm')"></el-input>
</el-form-item>
<!-- `checked` 爲 true 或 false -->
<el-checkbox v-model="checked">記住密碼</el-checkbox>
<br>
<br>
<div class="login-btn">
<el-button type="primary" @click="submitForm('ruleForm')">登陸</el-button>
</div>
</el-form>
</div>
複製代碼
//頁面加載調用獲取cookie值
mounted() {
this.getCookie();
},
methods: {
submitForm(formName) {
const self = this;
//判斷複選框是否被勾選 勾選則調用配置cookie方法
if (self.checked == true) {
console.log("checked == true");
//傳入帳號名,密碼,和保存天數3個參數
self.setCookie(self.ruleForm.username, self.ruleForm.password, 7);
}else {
console.log("清空Cookie");
//清空Cookie
self.clearCookie();
}
//與後端請求代碼,本功能不須要與後臺交互因此省略
console.log("登錄成功");
});
},
//設置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
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('='); //再次切割
//判斷查找相對應的值
if (arr2[0] == 'userName') {
this.ruleForm.username = arr2[1]; //保存到保存數據的地方
} else if (arr2[0] == 'userPwd') {
this.ruleForm.password = arr2[1];
}
}
}
},
//清除cookie
clearCookie: function() {
this.setCookie("", "", -1); //修改2值都爲空,天數爲負1天就行了
}
複製代碼
瀏覽器中的cookie信息以下圖,注意這裏的cookie的expire/Max-Age過時時間,這個時間是格林尼治標準時間GMT,世界統一的時間,GMT+8小時就是北京時間。(這裏不作加密功能)git