Detailed explanation of Vue login and logout

Detailed explanation of Vue login and logout

First, let’s take a look at our effect implementation process.

First log in to overview and business processes and related technical points

  • Layout of the record page
  • Create two Vue.js files
  • Let's make a login page and a registration page
  • Login page layout
  • Configuring Routes
  • Data Binding for Login Form
  • Validation rules for the login form
  • Resetting the login form
  • Login pre-authentication
  • Login component configuration pop-up prompt
  • Behavior after successful login
  • Save the token after login to the client's sessionStorage
  • Jump to the backend homepage through programmatic navigation, the routing address is the default path '/'
  • When logging out of our homepage, the component configuration pop-up window prompts us to delete our token using removeItem

Login business process

1. Enter your username and password on the login page

2. Call the backend interface for verification

3. After verification, jump to the project homepage according to the response status of the background

Login function implementation

1. First, we use the routing guard to verify the login and determine whether it is necessary to log in

{
    path:'/login',
    name:"login",
    component:login,
    meta:{
      login:true
    }
} 
  // Define meta-true where login is required to see if it is required if(to.matched.some(item=>item.meta.login)){//Login required console.log("Login required");
    if(isLogin){//1. Already logged in, directly pass if(data.error===400){//The backend tells you that the login failed next({name:'login'})
            localStorage.removeItem('token');
            return;
        }
        if(to.name==='login'){
            next({name:'Home'})
        }else{
            next()
        }
        return;
    }
    if(!isLogin && to.name==='login'){//2. Not logged in, but going to the login page next()
    }
    if(!isLogin && to.name !=='login'){//3. Not logged in, not the login page next({name:"login"})
    }
   }else{//No need to log in, go directly to next()
   }

2. For the form validation rules, we use the Element component library

Use Element to write our style layout in the template

 <div class="login-section">
    <!-- :rules="rules" -->
    <el-form
      label-position="top"
      label-width="100px" class="demo-ruleForm"
      :rules="rules"
      :model="rulesFrom"
      status-icon
      ref="ruleFrom"
    >
      <el-form-item label="username" prop="name">
        <!-- Use v-model to get the name entered by the user -->
        <el-input type="text" v-model="rulesFrom.name"></el-input>
      </el-form-item>
      <el-form-item label="password" prop="password"></el-form-item>
        <!-- Use v-model to get the password entered by the user -->
        <el-input type="password" v-model="rulesFrom.password"></el-input>
      </el-form-item>
      <el-form-item>
        <!-- Define submit event -->
        <el-button type="primary" @click="submitFrom('ruleFrom')">Submit</el-button>
        <el-button>Reset</el-button>
      </el-form-item>
    </el-form>
  </div>

Define validation rules for the form

See Element official website from form for details

Define in Data

rulesFrom:{
        name:'',
        password:''
      },
      rules:
        name:[
          // Validation rules {required:true,message:'Please enter your username',trigger:'blur'},
          {min:1,max:5,message:'Length is between 1 and 5 characters',trigger:'blur'}
        ],
        password:[
          {required:true,message:'Please enter your password',trigger:'blur'},
          {min:1,max:5,message:'Length is between 1 and 5 characters',trigger:'blur'}
        ]
      }

Define the submit event in methods

 // When we click submit, the method can be triggered to get everything in the form submitFrom(formName){
      this.$refs[formName].validate( (valid)=>{
        if(valid){
          // If the verification is passed, the user information and password will be returned to the backend login({
            name:this.rulesFrom.name,
            password:this.rulesFrom.password,
          }).then((data)=>{
            console.log(data);
            if(data.code===0){
              localStorage.setItem('token',data.data.token)
              window.location.href='/';
            }
            if(data.code===1){
              this.$message.error(data.message)
            }
          })
        }else{
          console.log('error submit!!');
          return false
        }
      })
    }

At this time, write the logout and convert it in the router beforeEach

const token = localStorage.getItem('token');
// ! ! Token is converted to Boolean type const isLogin=!!token;
// When entering the route, you need to return the token to the backend to verify whether it is legal const data = await userInfo();
    Store.commit('chageUserInfo',data.data)

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Example of implementing login and logout in Vue
  • Implementation of the login page of Vue actual combat record
  • Implementing the login page based on vue-cli3 and element
  • Example of implementing session and token login status verification using vue+koa2

<<:  Which one should I choose between MySQL unique index and normal index?

>>:  How to install the latest version of docker using deepin apt command

Recommend

Detailed steps for implementing timeout status monitoring in Apache FlinkCEP

CEP - Complex Event Processing. The payment has n...

How to display the border when td is empty

Previously, I summarized how to use CSS to achieve...

A brief discussion on the magical uses of CSS pseudo-elements and pseudo-classes

CSS plays a very important role in a web page. Wi...

Detailed explanation of web page loading progress bar (recommended)

(When a web page is loading, sometimes there is t...

MySQL grouping queries and aggregate functions

Overview I believe we often encounter such scenar...

Common symbols in Unicode

Unicode is a character encoding scheme developed ...

How to set an alias for a custom path in Vue

How to configure custom path aliases in Vue In ou...

Why Google and Facebook don't use Docker

The reason for writing this article is that I wan...

Solution to nginx not jumping to the upstream address

Preface Today I encountered a very strange proble...

MySQL database transaction example tutorial

Table of contents 1. What is a transaction? 2. Th...

Three implementation methods of Mysql copy table and grant analysis

How to quickly copy a table First, create a table...

Navicat for MySQL 15 Registration and Activation Detailed Tutorial

1. Download Navicat for MySQL 15 https://www.navi...

Div nested html without iframe

Recently, when doing homework, I needed to nest a ...