使用 cookie 实现记住密码功能

一、登陆页面

1.checkbox+button

<el-checkbox v-model="AccountForm.checked">记住密码</el-checkbox>
<el-button type="primary" style="width: 372px" @click="submitForm()">登录</el-button>

2.data

  data () {
    return {
      AccountForm: {
        userName: '',
        password: '',
        checked: true
      }
    }
  } 

3.mounted

  mounted () {
    this.getCookie()
  },

4.methods

  methods: {
    submitForm () {
      let that = this
      let userName = that.AccountForm.userName
      let password = that.AccountForm.password
      let checked = that.AccountForm.checked

      localStorage.setItem('userName', userNameData)
      localStorage.setItem('role', role)
      localStorage.setItem('userToken', token)

      // 判断记住密码的复选框是否被勾选,勾选则调用配置cookie方法
      if (checked === true) {
        // 传入账号名,密码,和保存天数3个参数
        // 将密码进行加密
        let CryptoJS = require('crypto-js')
        let ciphertext = CryptoJS.AES.encrypt(password, 'secret key 123').toString()
        console.log('加密密码:', ciphertext)
        // 将已加密密码保存在cookie中
        that.setCookie(userName, ciphertext, 7)
      } else {
        console.log('清空Cookie')
        // 清空Cookie
        that.clearCookie()
      }
    },

    // 设置cookie
    setCookie (saveName, savepwd, exdays) {
      let exDate = new Date() // 获取时间
      exDate.setTime(exDate.getTime() + 24 * 60 * 60 * 1000 * exdays) // 保存的天数
      // 字符串拼接cookie
      window.document.cookie = 'userName' + '=' + saveName + ';path=/;expires=' + exDate.toGMTString()
      window.document.cookie = 'userPwd' + '=' + savepwd + ';path=/;expires=' + exDate.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('=') // 再次切割
          // 判断查找相对应的值
          if (arr2[0] === 'userName') {
            this.AccountForm.userName = arr2[1] // 保存到保存数据的地方
          } else if (arr2[0] === 'userPwd') {
            // 将cookie中的密码进行解密
            let CryptoJS = require('crypto-js')
            let bytes = CryptoJS.AES.decrypt(arr2[1], 'secret key 123')
            let originalText = bytes.toString(CryptoJS.enc.Utf8)
            console.log('解密密码:', originalText)
            // 将解密密码进行填充
            this.AccountForm.password = originalText
          }
        }
      }
    },

    // 清除cookie
    clearCookie () {
      this.setCookie('', '', -1) // 修改2值都为空,天数为负1天就好了
    }
  }

二、退出登录页面

1.button

<a @click="exitLoginFun">退出登录</a>

2.methods

exitLoginFun () {
  localStorage.removeItem('userName')
  localStorage.removeItem('role')
  localStorage.removeItem('userToken')
}

END

猜你喜欢

转载自blog.csdn.net/Dora_5537/article/details/88321677
今日推荐