cookie 储存用户名及密码
mounted() {
this.getCookie()
},
methods: {
async submit() {
// 判断是否需要记住密码
if (this.remember === true) {
// 传入账号名,密码,和保存天数3个参数
this.setCookie(this.username, this.password, 7)
} else {
// 清空Cookie
this.clearCookie()
}
// 登录提交代码
...
},
// 设置cookie
setCookie(name, pwd, exdays) {
var now= new Date() // 获取时间
now.setTime(now.getTime() + 24 * 60 * 60 * 1000 * exdays) // 保存的天数
// 字符串拼接cookie' ;toGMTString() 方法可根据格林威治时间 (GMT) 把 Date 对象转换为字符串,并返回结果
window.document.cookie = 'userName' + '=' + name + ';time=' + now.toGMTString()
window.document.cookie = 'userPwd' + '=' + pwd + ';time=' + now.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.username = arr2[1] // 保存到保存数据的地方
} else if (arr2[0] === 'userPwd') {
this.password = arr2[1]
}
}
}
},
// 清除cookie
clearCookie: function() {
this.setCookie('', '', -1) // 修改2值都为空,天数为负1天就好了
}
}