您的位置:首页 > 其它

使用 cookie 实现记住密码功能

2019-03-07 21:59 183 查看

一、登陆页面

1.checkbox+button

[code]<el-checkbox v-model="AccountForm.checked">记住密码</el-checkbox>
[code]<el-button type="primary" style="width: 372px" @click="submitForm()">登录</el-button>

2.data

[code]  data () {
return {
AccountForm: {
userName: '',
password: '',
checked: true
}
}
}

3.mounted

[code]  mounted () {
this.getCookie()
},

4.methods

[code]  methods: {
submitForm () {
let that = this
let userName = that.AccountForm.userName
let password = that.AccountForm.password
let checked = that.AccountForm.checked

localStorage.setItem('userName', userNameData)
localStorage.setItem('role', role)
localStorage.setItem('userToken', token)

// 判断记住密码的复选框是否被勾选,勾选则调用配置cookie方法
if (checked === true) {
// 传入账号名,密码,和保存天数3个参数
// 将密码进行加密
let CryptoJS = require('crypto-js')
let ciphertext = CryptoJS.AES.encrypt(password, 'secret key 123').toString()
console.log('加密密码:', ciphertext)
// 将已加密密码保存在cookie中
that.setCookie(userName, ciphertext, 7)
} else {
console.log('清空Cookie')
// 清空Cookie
that.clearCookie()
}
},

// 设置cookie
setCookie (saveName, savepwd, exdays) {
let exDate = new Date() // 获取时间
exDate.setTime(exDate.getTime() + 24 * 60 * 60 * 1000 * exdays) // 保存的天数
// 字符串拼接cookie
window.document.cookie = 'userName' + '=' + saveName + ';path=/;expires=' + exDate.toGMTString()
window.document.cookie = 'userPwd' + '=' + savepwd + ';path=/;expires=' + exDate.toGMTString()
},

// 读取cookie
getCookie () {
if (document.cookie.length > 0) {
let arr = document.cookie.split('; ') // 这里显示的格式需要切割一下自己可输出看下
for (let i = 0; i < arr.length; i++) {
let arr2 = arr[i].split('=') // 再次切割
// 判断查找相对应的值
if (arr2[0] === 'userName') {
this.AccountForm.userName = arr2[1] // 保存到保存数据的地方
} else if (arr2[0] === 'userPwd') {
// 将cookie中的密码进行解密
let CryptoJS = require('crypto-js')
let bytes = CryptoJS.AES.decrypt(arr2[1], 'secret key 123')
let originalText = bytes.toString(CryptoJS.enc.Utf8)
console.log('解密密码:', originalText)
// 将解密密码进行填充
this.AccountForm.password = originalText
}
}
}
},

// 清除cookie
clearCookie () {
this.setCookie('', '', -1) // 修改2值都为空,天数为负1天就好了
}
}

二、退出登录页面

1.button

[code]<a @click="exitLoginFun">退出登录</a>

2.methods

[code]exitLoginFun () {
localStorage.removeItem('userName')
localStorage.removeItem('role')
localStorage.removeItem('userToken')
}

3.style

[code]<style scoped>
a:-webkit-any-link {
cursor: pointer;
text-decoration: none;
}
a:hover {
cursor: pointer;
color: #76c7f4;
}
</style>

END

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: