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

发布于:2025-03-26 ⋅ 阅读:(30) ⋅ 点赞:(0)

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


一、手动存储

login.vue

提示:

// 设置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

// coolie存储
import VueCookies from 'vue-cookies'
Vue.use(VueCookies)

login.vue

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")
},