vue+CryptoJS+cookie實現儲存賬號密碼
阿新 • • 發佈:2020-11-18
安裝依賴
npm i crypto-js --save
HTML
<el-input v-model="username" placeholder="使用者名稱"></el-input> <el-input v-model="password" placeholder="密碼"></el-input>
<el-checkbox v-model="checked">記住密碼</el-checkbox>
JS
mounted() { this.getCookie(); },
//表單提交方法 submit( ){if (that.checked == true) { //傳入賬號,密碼,儲存天數 that.setCookie(values.username, values.password, 7); } else { //清空Cookie that.clearCookie(); } }
//設定cookie方法 setCookie(username, password, days) { var text = CryptoJS.AES.encrypt(password, 'secret key 123'); //使用CryptoJS方法加密 var exdate = new Date(); //獲取時間 exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * days); //儲存的天數 //字串拼接存入cookie document.cookie = "username" + "==" + username + ";path=/;expires=" + exdate.toGMTString(); document.cookie= "password" + "==" + text + ";path=/;expires=" + exdate.toGMTString(); },
//讀取cookie getCookie() { if (document.cookie.length > 0) { var arr = document.cookie.split('; '); //這裡顯示的格式需要切割一下自己可輸出看下 for (var i = 0; i < arr.length; i++) { var arr2 = arr[i].split('=='); //再次切割 //這裡會切割出以username為第0項的陣列、以password為第0項的陣列,判斷查詢相對應的值 if (arr2[0] == 'adminusername') { this.form.setFieldsValue({ username: arr2[1], }); } else if (arr2[0] == 'adminpassword') { //拿到拿到加密後的密碼arr2[1]並解密 var bytes = CryptoJS.AES.decrypt(arr2[1].toString(), 'secret key 123'); var plaintext = bytes.toString(CryptoJS.enc.Utf8); //拿到解密後的密碼(登入時輸入的密碼) this.form.setFieldsValue({ password: plaintext, }); } } } },
//清除cookie clearCookie() { this.setCookie("", "", -1); //賬號密碼置空,天數置0 }