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

Super detailed MySQL usage specification sharing

Recently, there have been many database-related o...

MySQL database advanced query and multi-table query

MySQL multi-table query Add a worksheet -- User t...

Vue implements video upload function

This article example shares the specific code of ...

Complete example of vue polling request solution

Understanding of polling In fact, the focus of po...

HTML marquee tag usage examples

This tag is not part of HTML3.2 and only supports ...

JavaScript setTimeout and setTimeinterval use cases explained

Both methods can be used to execute a piece of ja...

How to package the uniapp project as a desktop application

Installing Electron cnpm install electron -g Inst...

...

How to implement multiple parameters in el-dropdown in ElementUI

Recently, due to the increase in buttons in the b...

A brief discussion on how to choose and combine div and table

Page layout has always been my concern since I st...

Nodejs converts JSON string into JSON object error solution

How to convert a JSON string into a JSON object? ...

Implementation steps for Docker deployment of SpringBoot applications

Table of contents Preface Dockerfile What is a Do...

SQL uses ROW_NUMBER() OVER function to generate sequence number

Syntax: ROW_NUMBER() OVER(PARTITION BY COLUMN ORD...