实现,勾选多选框记住密码
实现思路是判断是否点击记住密码,点击就将账户和密码写到cookie中,设置存储时间,下次登录就会自动记住密码点击登录按钮就可以登录,若未选择记住密码,则不会记住密码
记住一点:密码和账户需要加密保存,保证安全。
<el-checkbox v-model="checked" class="font-16 text-green hk-cursor">记住密码</el-checkbox>
methods设置cookie
我用的是Base64加密的
安装Base64
npm install --save js-base64
引入basse64
let Base64 = require('js-base64').Base64
<el-form-item prop="phone">
<el-input type="text" v-model="ruleForm.phone" autocomplete="off" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off" placeholder="确认密码"></el-input>
</el-form-item>
<el-checkbox v-model="checked" class="font-16 text-green hk-cursor">记住密码</el-checkbox>
data () {
rweturn {
// 记住密码checked
checked: false,
ruleForm: {
name: '',
pass: '',
phone: '',
code: ''
},
}
}
主要的逻辑代码在这里,有些混乱,多多担待,
// 记住密码读取信息
getCookie (cookieName) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(cookieName + '=')
if (c_start != -1) {
c_start = c_start + cookieName.length + 1
var c_end = document.cookie.indexOf(';', c_start)
if (c_end == -1)
c_end = document.cookie.length
return unescape(document.cookie.substring(c_start, c_end))
}
}
return ''
},
// 设置
setCookie(key, data, time) {
if (!key) {
return
}
let expires = 'Tue, 19 Jan 2038 03:14:07 GMT'
if (time) {
let date
if (isType(time, 'Date')) {
date = time
} else {
date = new Date()
date.setTime(date.getTime() + time * 60000)
}
expires = date.toGMTString()
}
data = JSON.stringify(data)
doc.cookie =
escape(key) + '=' + escape(data) + '; expires=' + expires + '; path=/'
}
delCookie(c_name){
setCookie(c_name, undefined, -1)
}
// 请求后台登录
myForm () {
submitForm (ruleForm) {
let accountInfo = ''
let phone = this.ruleForm.phone
let password = this.ruleForm.pass
let newaccount = Base64.encode(phone)
let newPassord = Base64.encode(password)
if (this.checked == true) {
console.log('选择记住密码', this.checked == true)
// 将加密后的密码存入cookie对象中
accountInfo = newaccount + '&' + newPassord
// 传入账户和密码,保存5天
this.setCookie('accountInfo', accountInfo, 1440 * 5)
} else {
console.log('清空cookie')
// 清空Cookie
this.delCookie('accountInfo')
}
// 请求数据
}
// 预读取cookie中用户信息
loadAccountInfo () {
let self = this
// admin%26U2FsdGVkX1+/ZtAGWFVi37gNwA7TUZmQM+yazInCPxs%3D
let accountInfo = this.getCookie('accountInfo')
console.log(accountInfo)
// 如果cookie里没有账号信息
if (Boolean(accountInfo) == false) {
console.log('cookie中没有检测到用户账号信息!')
return false
} else {
// 如果cookie里有账号信息
console.log('cookie中检测到账号信息!现在开始预填写!')
let userName = ''
let passWord = ''
let index = accountInfo.indexOf('&')
console.log(accountInfo)
userName = accountInfo.substring(0, index)
passWord = accountInfo.substring(index + 1)// 拿到加密后的密码
// 解密
// var bytes = Base64.decode(passWord)
// 拿到解密后的密码(登录时输入的密码)
self.ruleForm.phone = Base64.decode(userName)
self.ruleForm.pass = Base64.decode(passWord)
self.checked = true
}
}