The idea and process of Vue to realize the function of remembering account and password

The idea and process of Vue to realize the function of remembering account and password

Implementation ideas

If the user checks the "Remember Me" option when logging in, the login name and password (encrypted) will be saved in the local cache. The next time the login page is loaded, the saved account and password (need to be decrypted) will be automatically obtained and echoed to the login input box.

There are three ways to store account passwords:

1. sessionStorage (not recommended)

1). Only valid in the current session, it will be cleared after closing the browser window.

2). The storage data size is generally 5MB

3). No interactive communication with the server

2. localStorage

1). Unless you actively clear the information in localStorage, it will always exist and will still exist when you close the browser window and start it next time.

2). The storage data size is generally 5MB

3). No interactive communication with the server

3. Cookies

1). You can manually set the expiration date, and it will become invalid after the expiration date. No expiration time is set, and it is cleared after closing the browser window

2). The storage data size is generally 4K

3). Each request will be sent to the server

Here we mainly introduce the second and third methods of use.

Functional interface

<el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="100px" class="loginForm demo-ruleForm">
  <!-- Account -->
  <el-form-item label="Account" prop="userId" autocomplete="on">
    <el-input v-model="loginForm.userId" placeholder="Please enter your account number"></el-input>
  </el-form-item>
  <!-- Password -->
  <el-form-item label="password" prop="password">
    <el-input type="password" v-model="loginForm.password" placeholder="Please enter your password" @keyup.enter="submitForm('loginForm')"></el-input>
  </el-form-item>
  <div class="tip">
    <!-- Remember Me -->
    <el-checkbox v-model="checked" class="rememberMe">Remember me</el-checkbox>
    <!-- Retrieve Password -->
    <el-button type="text" @click="open()" class="forgetPw">Forgot your password? </el-button>
  </div>
  <!-- Login -->
  <el-form-item>
    <el-button type="primary" @click="submitForm('loginForm')" class="submit-btn">Login</el-button>
  </el-form-item>
</el-form>

Specific implementation of the function of remembering account and password

Password encryption

To improve security, passwords need to be encrypted before storage. There are many encryption methods available. I chose base64 here.

npm install base64 dependency

//Install npm install --save js-base64
//Introduce const Base64 = require("js-base64").Base64

localStorage

export default {
  data() {
    return {
      loginForm: {
        userId: "",
        password: "",
      },
      checked: false,
    };
  },
  mounted() {
    let username = localStorage.getItem("userId");
    if (username) {
      this.loginForm.userId = localStorage.getItem("userId");
      this.loginForm.password = Base64.decode(localStorage.getItem("password")); // base64 decryption this.checked = true;
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          /* ------ Storage of account and password ------ */
          if (this.checked) {
            let password = Base64.encode(this.loginForm.password); // base64 encryption localStorage.setItem("userId", this.loginForm.userId);
            localStorage.setItem("password", password);
          } else {
            localStorage.removeItem("userId");
            localStorage.removeItem("password");
          }
          /* ------ http login request ------ */
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};

Cookies

export default {
  data() {
    return {
      loginForm: {
        userId: "",
        password: "",
      },
      checked: false,
    };
  },
  mounted() {
    this.getCookie();
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          /* ------ Storage of account and password ------ */
          if (this.checked) {
            let password = Base64.encode(this.loginForm.password); // base64 encryption this.setCookie(this.loginForm.userId, password, 7);
          } else {
            this.setCookie("", "", -1); // Modify both values ​​to be empty, and the number of days to be negative 1 day}
          /* ------ http login request ------ */
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    
    // Set cookies
    setCookie(userId, password, days) {
      let date = new Date(); // Get time date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * days); // Number of days to save // ​​String concatenation cookie
      window.document.cookie =
        "userId" + "=" + userId + ";path=/;expires=" + date.toGMTString();
      window.document.cookie =
        "password" + "=" + password + ";path=/;expires=" + date.toGMTString();
    },
    
    // Read the cookie and echo the username and password to the input box getCookie() {
      if (document.cookie.length > 0) {
        let arr = document.cookie.split("; "); //Split into independent "key=value" forms for (let i = 0; i < arr.length; i++) {
          let arr2 = arr[i].split("="); // Split again, arr2[0] is the key value, arr2[1] is the corresponding value
          if (arr2[0] === "userId") {
            this.loginForm.userId = arr2[1];
          } else if (arr2[0] === "password") {
            this.loginForm.password = Base64.decode(arr2[1]); // base64 decryption this.checked = true;
          }
        }
      }
    },
  },
};

Summarize

This concludes this article about the ideas and process of implementing the login and password remembering function in Vue. For more relevant content about implementing the login and password remembering function in Vue, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue learning road login registration example code
  • Vue.js implements user comment, login, registration, and information modification functions
  • Detailed explanation of vue login registration example
  • How to register and keep logged in in Vue
  • Sample code for implementing login and registration template in Vue

<<:  Detailed explanation of single-choice and multiple-choice selection in HTML select tag

>>:  Jenkins packaging microservices to build Docker images and run them

Recommend

Solution to Incorrect string value in MySQL

Many friends will report the following error when...

Methods for optimizing Oracle database with large memory pages in Linux

Preface PC Server has developed to this day and h...

Solutions for high traffic websites

First: First, confirm whether the server hardware ...

IE6 space bug fix method

Look at the code: Copy code The code is as follows...

Several ways to shut down Hyper-V service under Windows 10

When using VMware Workstation to open a virtual m...

How to migrate mysql storage location to a new disk

1. Prepare a new disk and format it with the same...

Design theory: the basics of font design

<br />Words are the inevitable product of hu...

A detailed analysis of the murder caused by a misplaced double quote in MySQL

1. Introduction Recently, I often encounter devel...

How to set up Referer in Nginx to prevent image theft

If the server's images are hotlinked by other...

Determine whether MySQL update will lock the table through examples

Two cases: 1. With index 2. Without index Prerequ...

How to use dd command in Linux without destroying the disk

Whether you're trying to salvage data from a ...

Solution for FileZilla 425 Unable to connect to FTP (Alibaba Cloud Server)

Alibaba Cloud Server cannot connect to FTP FileZi...

Method of using MySQL system database for performance load diagnosis

A master once said that you should know the datab...