vue實現加記住密碼功能
阿新 • • 發佈:2021-06-23
實現功能:
1.記住密碼勾選,點登陸時,將賬號和密碼儲存到cookie,下次登陸自動顯示到表單內
2.不勾選,點登陸時候則清空之前儲存到cookie的值,下次登陸需要手動輸入
大體思路就是通過存/取/刪cookie實現的;每次進入登入頁,先去讀取cookie,如果瀏覽器的cookie中有賬號資訊,就自動填充到登入框中,存cookie是在登入成功之後,判斷當前使用者是否勾選了記住密碼,如果勾選了,則把賬號資訊存到cookie當中,效果圖如上:
直接上主要的程式碼
HTML部分
<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>
JS部分
//頁面載入呼叫獲取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小時就是北京時間。(這裡不做加密功能)