Vue 登录 记住密码,设置存储时间

Vue 登录 记住密码,设置存储时间


一、手动存储

login.vue

提示:

javascript 复制代码
// 设置cookie方法
setCookie(loginName, password, days) {
  let text = encryptDes(password, '@des123')//使用des方法加密,秘钥'@des123'
  let saveDays = new Date() //获取时间
  saveDays.setTime(saveDays.getTime() + 24 * 60 * 60 * 1000 * days) //保存的天数
  // 字符串拼接存入cookie
  window.document.cookie = 'loginName' + '=' + loginName + ';path=/;saveDays=' + saveDays.toGMTString()
  window.document.cookie = 'password' + '=' + text + ';path=/;saveDays=' + saveDays.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('=') // 再次切割
      // 这里会切割出以loginName为第0项的数组、以password为第0项的数组,判断查找相对应的值
      if (arr2[0] == 'loginName') {
        this.loginForm.loginName = arr2[1] // 拿到账号
      } else if (arr2[0] == 'password') {
        // 拿到拿到加密后的密码arr2[1]并解密
        let bytes = decryptDes(arr2[1].toString(), '@des123')
        // let plaintext = bytes.toString(CryptoJS.enc.Utf8); // 拿到解密后的密码(登录时输入的密码)
        // this.loginForm.password = plaintext;
        this.loginForm.password = bytes
      }
    }
  }
},
// 清除cookie
clearCookie() {
  this.setCookie('', '', 0) //账号密码置空,天数置0
},

二、使用vue-cookies插件

main.js

javascript 复制代码
// coolie存储
import VueCookies from 'vue-cookies'
Vue.use(VueCookies)

login.vue

javascript 复制代码
if (this.isRememberPwd === true) { // 传入账号,密码,保存天数
  this.setLocal(this.loginName, this.password)
} else { // 清除cookie
  this.removeLocal()
}

// 设置cookies
setLocal(loginName, password) {
  let text = encryptDes(password, '@des123')//使用des方法加密,秘钥'@des123'
  const days = '60 * 60 * 24 * 7' // 60秒*60分*24小时*7天
  this.$cookies.set('loginName', loginName, days)
  this.$cookies.set('password', text, days)
},
// 读取cookies
getLocal() {
  if (this.$cookies.get("loginName"))
    this.loginName = this.$cookies.get("loginName") // 拿到账号
  if (this.$cookies.get("password"))
    this.password = decryptDes(this.$cookies.get("password"), '@des123') // 拿到密码
},
// 清除cookie
removeLocal() {
  this.$cookies.remove("loginName")
  this.$cookies.remove("password")
},
相关推荐
梦想CAD控件2 分钟前
在线CAD开发包结构与功能说明
前端·javascript·vue.js
张拭心6 分钟前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
时光不负努力7 分钟前
typescript常用的dom 元素类型
前端·typescript
小怪点点12 分钟前
大文件切片上传
前端
时光不负努力13 分钟前
TS 常用工具类型
前端·javascript·typescript
SuperEugene15 分钟前
Vue状态管理扫盲篇:Vuex 到 Pinia | 为什么大家都在迁移?核心用法对比
前端·vue.js·面试
张拭心17 分钟前
Android 17 来了!新特性介绍与适配建议
android·前端
徐小夕22 分钟前
pxcharts-vue:一款专为 Vue3 打造的开源多维表格解决方案
前端·vue.js·github
Hilaku22 分钟前
我会如何考核一个在简历里大谈 AI 提效的高级前端?
前端·javascript·面试
进击的尘埃35 分钟前
Vue3 中 emit 能 await 吗?事件机制里的异步陷阱
javascript