vue登录页实现使用cookie记住7天密码功能(思路)

4,615 阅读3分钟

问题描述

项目的登录页中,会有要求记住7天密码的功能,本篇文章记录一下写法,主要是使用cookie,注释我写的很详细了,大家可以看一下我写的注释的步骤,还是比较详细的。亲测有效

html部分

代码图示

效果图示

代码粘贴

            <el-form
              ref="form"
              :model="form"
              label-width="80px"
              label-position="top"
              @submit.native.prevent
            >
              <el-form-item label="用户名/账号">
                <div class="userError">
                  <el-input
                    size="mini"
                    v-model.trim="form.userName"
                    clearable
                  ></el-input>
                </div>
              </el-form-item>
              <el-form-item label="密码">
                <div class="pwdError">
                  <el-input
                    size="mini"
                    v-model.trim="form.loginPwd"
                    clearable
                    show-password
                  ></el-input>
                </div>
              </el-form-item>
              <el-checkbox label="记住账号" v-model="isRemember"></el-checkbox>
              <el-button native-type="submit" size="mini" @click="loginPage"
                >登录</el-button
              >
            </el-form>

js部分

代码粘贴

export default {
  name: "login",
  data() {
    return {
      form: {
        userName: '',
        loginPwd: '',
      },
      isRemember: false,
    };
  },
  mounted() {
    // 第1步,在页面加载的时候,首先去查看一下cookie中有没有用户名和密码可以用
    this.getCookie();
  },
  methods: {
    /*  第3步,当用户执行登录操作的时候,先看看用户名密码对不对
              若不对,就提示登录错误
              若对,就再看一下用户有没有勾选记住密码
                    若没勾选,就及时清空cookie,回到最初始状态
                    若勾选了,就把用户名和密码存到cookie中并设置7天有效期,以供使用
                      (当然也有可能是更新之前的cookie时间)
    */
    async loginPage() {
      // 发请求看看用户输入的用户名和密码是否正确
      const res = await this.$api.loginByUserName(this.form)
      if(res.isSuccess == false){
        this.$message.error("登录错误")
      }
      else{
        const self = this;
        // 第4步,若复选框被勾选了,就调用设置cookie方法,把当前的用户名和密码和过期时间存到cookie中
        if (self.isRemember === true) {
          // 传入账号名,密码,和保存天数(过期时间)3个参数
          //  1/24/60 测试可用一分钟测试,这样看着会比较明显
          self.setCookie(this.form.userName, this.form.loginPwd, 1/24/60);
          // self.setCookie(this.form.userName, this.form.loginPwd, 7); // 这样就是7天过期时间
        } 
        // 若没被勾选就及时清空Cookie,因为这个cookie有可能是上一次的未过期的cookie,所以要及时清除掉
        else {
          self.clearCookie();
        }
        // 当然,无论用户是否勾选了cookie,路由该跳转还是要跳转的
        this.$router.push({
          name: "project",
        });
      }
    },
    // 设置cookie
    setCookie(username, password, exdays) {
      var exdate = new Date(); // 获取当前登录的时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); // 将当前登录的时间加上七天,就是cookie过期的时间,也就是保存的天数
      // 字符串拼接cookie,因为cookie存储的形式是name=value的形式
      window.document.cookie = "userName" + "=" + username + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie = "userPwd" + "=" + password + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie = "isRemember" + "=" + this.isRemember + ";path=/;expires=" + exdate.toGMTString();
    },
    // 第2步,若cookie中有用户名和密码的话,就通过两次切割取出来存到form表单中以供使用,若是没有就没有
    getCookie: function () {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); //因为是数组所以要切割。打印看一下就知道了
        // console.log(arr,"切割");
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); // 再次切割
          // console.log(arr2,"切割2");
          // // 判断查找相对应的值
          if (arr2[0] === "userName") {
            this.form.userName = arr2[1]; // 转存一份保存用户名和密码
          } else if (arr2[0] === "userPwd") {
            this.form.loginPwd = arr2[1];//可解密
          } else if (arr2[0] === "isRemember") {
            this.isRemember = Boolean(arr2[1]);
          }
        }
      }
    },
    // 清除cookie
    clearCookie: fu![image](/img/bVcOHhz)
      this.setCookie("", "", -1); // 清空并设置天数为负1天
    },
  },
};

cookie存储图示

总结

其实也很简单,就是设置一个过期时间,也就是cookie的失效的日期,当然中间需要有一些格式的处理,数据的加工。 细心的朋友会发现上述例子中没有加密,所以大家可以根据自己公司的情况,选择对应的加密的工具。当然这个做法更加适合后台管理系统,因为大多数的后台管理系统,都是要内网才能进入的。本文只是说一下思路,具体情况具体分析

补充,cookie是存在浏览器中,浏览器安装在电脑中,比如安装在C盘,所以cookie是存在C盘中的某个文件夹下,那个文件夹不仅有cookie,还有localStorage和sessionStorage和别的,具体哪个文件夹大家可以自己动手找一找。其实所谓的本地存储其实就是存在自己的电脑上。