Vue routing guard + cookie to verify whether the user is logged in when the page is redirected-(1) cookies

In the vue project, after the user logs in successfully, the user information will be stored in the cookie, and then jump to the home page. When the user is not logged in, directly enter the page address and the routing guard will detect whether the user information exists in the cookie. , Redirect to the login page to let the user log in. Next, start by configuring the cookie method.

First, create a new util / cookie.js file in the project as the js to store the cookie method

 

 

 Write the following code in cookie.js, the code encapsulates three methods, setCookie: store cookie; getCookie: read cookie; clearCookie: delete the specified cookie; finally export these three methods for global call, each line of code What exactly does it mean? You can watch the following tutorials: cookie tutorial one , cookie tutorial two , the explanation is very detailed.

/ * * 
 * @description to save cookies 
 * @param {Object} json objects that need to store cookies 
 * @param {Number} days how many days to store by default 
 * / 
function setCookie (json, days) {
     // set expiration time 
    let data = new Date (
         new Date (). GetTime () + days * 24 * 60 * 60 * 1000 
    ) .toUTCString (); 

    for ( var key in json) { 
        document.cookie = key + "=" + json [key] + " ; expires = "+ data; 
    } 
} 

/ * * 
 * @description get cookie 
 * @param {String} name need to get cookie key 
 * / 
function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) {
        return unescape(arr[2])
    } else {
        return null
    }
}

/** 
 * @description 删除cookie
 * @param {String} name 需要删除cookie的key
 */
function clearCookie(name) {
    let json = {};
    json[name] = '';
    setCookie(json, -1)
}

export default {
    setCookie,
    getCookie,
    clearCookie
}

Then introduce the cookie.js just written in main.js, and set the cookie field as a global variable through Vue.prototype

 

 After the introduction is complete, you can add or delete cookies by using this.cookie. Method name (value) on any page.

this.cookie.setCookie()   //存cookie

this.cookie.getCookie()  //读cookie

this.cookie.clearCookie()   //删cookie

First create a login page Login.vue in the project to write a login page. After successful login, use this.cookie.setCookie to store user information in the cookie.

<template>
  <div>
    <form action>
      <div>
        账号:
        <input type="text" v-model="name" />
      </div>
      <div>
        密码:
        <input type="password" v-model="password" />
      </div>
      <div>
        <button @click="login" type="submit">登录</button> 
      </div>
    </form>
  </div>
</template>

<script>

export default {
  data() {
    return {
      name: "",
      password: ""
    };
  },
  methods: {    
    login() {
        if (! this .name) { 
          alert ( "Please fill in your account" );
           return ; 
        } 
        if (! this .password) { 
          alert ( "Please enter your password" );
           return ; 
        } 
        if ( this .password && this .name) {
           // Send information to the setCookie method in json format, the method will loop through the json in a single data storage mode, and store it in the cookie multiple times 
      // Note: cookies do not support direct storage in json as
let loginInfo = { LoginName: this .name, openId: "asfafsfsfsdfsdfsdfdsf" } // Call the setCookie method and pass the data to be stored at the same time, save the number of days this .cookie.setCookie (loginInfo, 7 ) alert ( "Login successful" ) // Jump to the home page this . $ Router.replace ('/' ) } } } }; </ script>

After successful login, you can see the saved LoginName, openId, and their expiration time in the browser's cookie.

 

 

 

 After successful login, we jumped to the home.vue page and obtained the login name through this.getCookie ("LoginName").

 

 

 

 Then you need to clear the cookie when you click logout, and then return to the login page.

 

 Click to clear the cookie after logging out, and jump to the login page, now go to view the cookie

 

 Found that it is blank.

So far, our first step is basically completed, and then we must verify whether there is login information in the cookie when jumping, if not, we will not allow the jump and jump to the login page. That is to use the routing guard.

 

Guess you like

Origin www.cnblogs.com/songzxblog/p/12723892.html