How to use cookies to remember passwords for 7 days on the vue login page

How to use cookies to remember passwords for 7 days on the vue login page

Problem Description

In the login page of the project, there will be a function requiring you to remember the password for 7 days. This article records the writing method, mainly using cookies. The comments I wrote are very detailed. You can take a look at the steps of the comments I wrote, which are quite detailed. Proven effectiveness

HTML part

Code Diagram

Effect diagram

Paste code

      <el-form
       ref="form"
       :model="form"
       label-width="80px"
       label-position="top"
       @submit.native.prevent
      >
       <el-form-item label="Username/Account">
        <div class="userError">
         <el-input
          size="mini"
          v-model.trim="form.userName"
          clearable
         ></el-input>
        </div>
       </el-form-item>
       <el-form-item label="Password">
        <div class="pwdError">
         <el-input
          size="mini"
          v-model.trim="form.loginPwd"
          clearable
          show-password
         ></el-input>
        </div>
       </el-form-item>
       <el-checkbox label="Remember account" v-model="isRemember"></el-checkbox>
       <el-button native-type="submit" size="mini" @click="loginPage"
        >Login</el-button
       >
      </el-form>

js part

export default {
 name: "login",
 data() {
  return {
   form: {
    userName: '',
    loginPwd: '',
   },
   isRemember: false,
  };
 },
 mounted() {
  // Step 1, when the page is loaded, first check if there is a username and password in the cookie. This can be used with this.getCookie();
 },
 methods: {
  /* Step 3, when the user logs in, first check whether the username and password are correct. If not, prompt a login error. If correct, check whether the user has checked the remember password. If not, clear the cookie in time and return to the initial state. If checked, save the username and password in the cookie and set a 7-day validity period for use (of course, it may also be the cookie time before the update)
  */
  async loginPage() {
   // Send a request to see if the username and password entered by the user are correct const res = await this.$api.loginByUserName(this.form)
   if(res.isSuccess == false){
    this.$message.error("Login error")
   }
   else{
    const self = this;
    // Step 4, if the checkbox is checked, call the set cookie method to save the current username, password and expiration time to the cookie if (self.isRemember === true) {
     // Pass in the account name, password, and number of days to save (expiration time) as three parameters // 1/24/60 The test can be tested for one minute, which will be more obvious self.setCookie(this.form.userName, this.form.loginPwd, 1/24/60);
     // self.setCookie(this.form.userName, this.form.loginPwd, 7); // This will expire in 7 days} 
    // If it is not checked, clear the cookie in time, because this cookie may be the last unexpired cookie, so it should be cleared in time else {
     self.clearCookie();
    }
    // Of course, regardless of whether the user has checked the cookie, the route will still be redirected this.$router.push({
     name: "project",
    });
   }
  },
  // Set cookies
  setCookie(username, password, exdays) {
   var exdate = new Date(); // Get the current login timeexdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); // Add seven days to the current login time to get the cookie expiration time, which is the number of days to save. // String concatenation cookies, because cookies are stored in the form of name=valuewindow.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();
  },
  // Step 2, if there is a username and password in the cookie, it will be cut twice and saved in the form for use. If not, there will be no getCookie: function () {
   if (document.cookie.length > 0) {
    var arr = document.cookie.split("; "); //Because it is an array, it needs to be cut. Print it and you will know // console.log(arr,"cut");
    for (var i = 0; i < arr.length; i++) {
     var arr2 = arr[i].split("="); // Split again // console.log(arr2,"Split 2");
     // // Check the corresponding value if (arr2[0] === "userName") {
      this.form.userName = arr2[1]; // Save a copy of the username and password} else if (arr2[0] === "userPwd") {
      this.form.loginPwd = arr2[1]; // decryptable} else if (arr2[0] === "isRemember") {
      this.isRemember = Boolean(arr2[1]);
     }
    }
   }
  },
  // Clear cookies
  clearCookie: fu![image](/img/bVcOHhz)
   this.setCookie("", "", -1); // Clear and set the number of days to negative 1 day},
 },
};

Cookie storage diagram

Summarize

In fact, it is very simple. It is to set an expiration time, which is the date when the cookie expires. Of course, some format processing and data processing are required in the middle.

In addition, cookies exist in the browser, and the browser is installed in the computer, such as in the C drive, so cookies are stored in a folder in the C drive. That folder contains not only cookies, but also localStorage, sessionStorage and others. You can find the specific folder yourself. In fact, the so-called local storage actually exists on your own computer.

This is the end of this article about how to use cookies to remember passwords for 7 days on the vue login page. For more information about how to use cookies to remember passwords on the vue login page, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • PHP cookie working principle and example explanation
  • Python Selenium instance method for operating Cookies
  • Python crawler uses request library to process cookies
  • ASP.NET Core sample code using Cookie authentication
  • Detailed explanation of the working principle and application of cookies

<<:  Problems and solutions encountered when installing mininet on Ubuntu 16.04.4LTS

>>:  Detailed explanation of MySQL table name case-insensitive configuration method

Recommend

How to add Vite support to old Vue projects

1. Introduction I have taken over a project of th...

How to use the Linux seq command

1. Command Introduction The seq (Sequence) comman...

Introduction to the use of several special attribute tags in HTML

The following attributes are not very compatible w...

A brief discussion on MySQL temporary tables and derived tables

About derived tables When the main query contains...

About the usage and precautions of promise in javascript (recommended)

1. Promise description Promise is a standard buil...

Issues installing Python3 and Pip in ubuntu in Docker

text 1) Download the Ubuntu image docker pull ubu...

A detailed introduction to HTML page loading and parsing process

The order in which the browser loads and renders H...

Example code of html formatting json

Without further ado, I will post the code for you...

How to configure two-way certificate verification on nginx proxy server

Generate a certificate chain Use the script to ge...

JavaScript Advanced Closures Explained

Table of contents 1. The concept of closure Addit...

5 solutions to CSS box collapse

First, what is box collapse? Elements that should...

Detailed Tutorial on Using xargs Command on Linux

Hello everyone, I am Liang Xu. When using Linux, ...

MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...