页面图示:
在这里插入图片描述
html:

<div class="clear">
  <div class="autoLogin">
    <el-checkbox v-model="checked" class="autoCheck">自动登录</el-checkbox>
    <span @click="clearCookie" class="forgetPwd">忘记密码</span>
  </div>
</div>

data:

checked: true, // 默认选中

初始化:

created () {
 this.getCookie()
},

获取以及使用cookie方法

// 设置cookie
setCookie (name, pwd, exdays) {
  var exdate = new Date()// 获取时间
  exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays)// 保存的天数
  // 字符串拼接cookie
  window.document.cookie = 'userName' + '=' + name + ';path=/;expires=' + exdate.toGMTString()
  window.document.cookie = 'userPwd' + '=' + pwd + ';path=/;expires=' + exdate.toGMTString()
},
// 读取cookie 将用户名和密码回显到input框中
getCookie () {
  if (document.cookie.length > 0) {
    var arr = document.cookie.split('; ')// 这里显示的格式需要切割一下自己可输出看下
    for (var i = 0; i < arr.length; i++) {
      var arr2 = arr[i].split('=')// 再次切割
      // 判断查找相对应的值
      if (arr2[0] === 'userName') {
        this.ruleForm.userName = arr2[1]// 保存到保存数据的地方
      } else if (arr2[0] === 'userPwd') {
        this.ruleForm.password = arr2[1]
      }
    }
  }
},
点击登录按钮的时候,判断是否勾选了自动登录(记住密码),对cookie做相应操作
if (this.checked) {
  // 传入账号名,密码,和保存天数3个参数
  this.setCookie(this.ruleForm.userName, this.ruleForm.password, 7)
} else {
  // 如果没有选中自动登录,那就清除cookie
  this.setCookie('', '', -1) // 修改2值都为空,天数为负1天就好了
}

如果点击忘记密码,则调用 this.setCookie(’’, ‘’, -1) 即可

把用追马的时间去种一片草原,来年一群马儿会不请自来!

Logo

前往低代码交流专区

更多推荐