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")
},
相关推荐
用户059540174462 小时前
把AI对话记忆存储测试从手工改成Playwright+pytest,覆盖率从20%提到96%,回归时间缩短90%
前端·css
kyriewen2 小时前
别再这样写TypeScript了——Code Review中最常见的8个反模式
前端·javascript·typescript
名字还没想好☜3 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
午安~婉3 小时前
GitHub Token/ GitHub Stats统计显示图异常
前端·github·vercel·github token
码云之上3 小时前
AI Agent 工程化总览篇:从 Prompt 到 Harness
前端·人工智能
2501_926978333 小时前
以说明书 DNA 为模板——完整 AGI 的结构图景
前端·人工智能·经验分享·笔记·ai写作
IT_陈寒3 小时前
Vite静态资源引用这个坑我踩得有点疼
前端·人工智能·后端
程序员黑豆4 小时前
鸿蒙应用开发:AttributeModifier 使用教程
前端·harmonyos
codeniu4 小时前
TRAE Work 实战 | 从"有个想法"到线上Demo,我全程只靠对话就完成了
前端·trae
妙码生花4 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(五十):增加管理员角色组管理
前端·后端·ai编程