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

Encapsulate the navigation bar component with Vue

Preface: Fully encapsulating a functional module ...

CentOS 8 installation diagram (super detailed tutorial)

CentOS 8 is officially released! CentOS fully com...

Javascript Basics: Detailed Explanation of Operators and Flow Control

Table of contents 1. Operator 1.1 Arithmetic oper...

Example code for Html layered box-shadow effect

First, let’s take a look at the picture: Today we...

An IE crash bug

Copy code The code is as follows: <style type=...

Tips to prevent others from saving as my web page and copying my site

Nowadays, copying websites is very common on the I...

Detailed explanation of the data responsiveness principle of Vue

This article is mainly for those who do not under...

How to make vue long list load quickly

Table of contents background Main content 1. Comp...

Javascript basics about built-in objects

Table of contents 1. Introduction to built-in obj...

Example sharing of anchor tag usage in HTML

Anchor tag usage: Linking to a specific location i...

How MySQL uses transactions

Basics A transaction is an atomic operation on a ...

How to remove the dotted border when clicking a link in FireFox

I encountered several browser compatibility issue...

MySQL learning record: bloody incident caused by KEY partition

Demand background Part of the data in the busines...