vue 中如何保存登录的账号密码

本文介绍了一种使用浏览器存储功能保存登录信息的方法,通过在页面加载时读取并填充账号密码,实现了自动登录的功能。代码演示了如何在Vue中设置和获取cookie。

这个问题只要是网站设计到登录的都会涉及到

1.解决问题的思路

借助浏览器的存储功能来实现保存登录的账号和密码,使页面进来的时候就去读取是否有账号和密码。

2.直接代码演示拿来即用

created() {
    // 在页面加载时从cookie获取登录信息
    const username = this.getCookie('username')
    const password = this.getCookie('Password')
    // 如果存在赋值给表单,并且将记住密码勾选
    if (username) {
      this.LoginRequest.UserName = username
      this.LoginRequest.Password = password
      this.checked = true
    }
  },
 methods: {
    // 是否记住记住密码
    setUserInfo() {
      if (this.checked) {
        this.setCookie('username', this.LoginRequest.UserName)
        this.setCookie('Password', this.LoginRequest.Password)
        this.setCookie('remember', this.checked)
      } else {
        this.setCookie('username', '')
        this.setCookie('Password', '')
      }
    },
    // 获取cookie
    getCookie: function(key) {
      if (document.cookie.length > 0) {
        var start = document.cookie.indexOf(key + '=')
        if (start !== -1) {
          start = start + key.length + 1
          var end = document.cookie.indexOf(';', start)
          if (end === -1) end = document.cookie.length
          return unescape(document.cookie.substring(start, end))
        }
      }
      return ''
    },
    // 保存cookie
    setCookie: function(cName, value, expiredays) {
      var exdate = new Date()
      exdate.setDate(exdate.getDate() + expiredays)
      document.cookie = cName + '=' + decodeURIComponent(value) +
            ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString())
    }
  }

有哪里不足的地方还请各位大佬留言指导

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值