vue项目实现记住密码到cookie功能
生活随笔
收集整理的這篇文章主要介紹了
vue项目实现记住密码到cookie功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
vue項目實現記住密碼到cookie功能(附源碼)
實現功能:
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");//清空Cookieself.clearCookie();}//與后端請求代碼,本功能不需要與后臺交互所以省略console.log("登陸成功");});},//設置cookiesetCookie(c_name, c_pwd, exdays) {var exdate = new Date(); //獲取時間exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天數//字符串拼接cookiewindow.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();window.document.cookie = "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();},//讀取cookiegetCookie: 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];}}}},//清除cookieclearCookie: function() {this.setCookie("", "", -1); //修改2值都為空,天數為負1天就好了}瀏覽器中的cookie信息如下圖,注意這里的cookie的expire/Max-Age過期時間,這個時間是格林尼治標準時間GMT,世界統一的時間,GMT+8小時就是北京時間。
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的vue项目实现记住密码到cookie功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: export default 和 exp
- 下一篇: 用localStorage实现登录时记住