02-Logon and Exit

Logon/Exit Function

1 Logon overview

1.1 Login Business Process
  1. Enter the appropriate user name and password on the login page
  2. Call back-end interface for validation
  3. Jump to project home page based on background response status after validation
1.2 Relevant technical points of login business
  1. http is stateless
  2. Record status on client side by cookie
  3. Logging status on the server side through session
  4. Maintain state by token

Recommend cookie s and session s if cross-domain issues do not exist between servers and clients

token is recommended if there are cross-domain issues between the server and the client

2 Login-token Principle Analysis

3 Login Function Implementation

1 Landing Page Layout

Layout through Element-UI components

  • el-form
  • el-form-item
  • el-input
  • el-button
  • Font Icon

2 Comb project structure
  1. First open the terminal in the project root path to check if the working directory is clean

git status

2. Create login Branch

git checkout -b login

View all branches of the current project

3. Clean up projects

  • delete App.vue Content in file except skeleton
  • Delete under router fileIndex.jsRouting rules in
  • Delete component files under the views folder
  • Delete component files under the components folder
  1. Create Login Component
  • Create login components under the components folder
  <div>Login Component</div>

export default {
  name: 'Login'

<style lang="less" scoped>

  • Introducing Login components into routing and setting corresponding routing rules
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'


const routes = [
  { path: '/login', component: Login }

const router = new VueRouter({

export default router
  • Add Routing Placeholder to App Root Component
  <div id="app">
<!--    Routing Placeholder-->

Login component content is displayed when the corresponding routing rule is accessed

  • Routing Redirection

Setting redirection in route matching rules

const routes = [
  //Set Routing Redirection
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login }
  • Set Background Color
<style lang="less" scoped>
  background-color: #2b4b6b;

At this point, the rendered Login component will not fill the full screen
So you need to create a new css folder under the assets folder
Create a new global CSS file under the CSS folderGlobal.css

/*Global Style Sheet*/
html, body, #app {
    height: 100%;
    margin: 0;
    padding: 0;

In Global Entry FileMain.jsImport inGlobal.css

// Import Global Style Sheet
import './assets/css/global.css'

Returning to the Login component at this point will add login_The div add style height of the container style class is 100% so that it fills the full screen

  • Draw the central login box

Add a div box to the login component to style it

  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  • Draw Avatar

Add logo's div box to introduce pictures and add styles

.avatar_box {
    height: 130px;
    width: 130px;
    border:1px solid #eeeeee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #dddddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eeeeee;

  • Draw login form

Under the plugins folderElement.jsIntroduce Form and FormItem as needed in the file

import Vue from 'vue'
import { Button } from 'element-ui'
import { Form } from 'element-ui'
import { FormItem } from 'element-ui'
import { Input } from 'element-ui'

  • Find the Form form on the Element-UI website and paste the code into the Login component

<!--      Landing Form Area-->
     <el-form label-width="0" class="login_form">
<!--        User name-->
         <el-input ></el-input>
<!--        Password-->
         <el-input ></el-input>
<!--        Button-->
       <el-form-item class="btns">
         <el-button type="primary">Sign in</el-button>
         <el-button type="info">Reset</el-button>

Add the appropriate style

.login_form {
  padding: 0 20px;
  width: 100%;
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
.btns {
  display: flex;
  justify-content: flex-end;

  • Add Font Icon

Similarly, go to the Elemen-UI website to find font icons first
If you find that there are not enough icons, you can choose a third-party icon library- Ali Vector Icon Library

Introducing the base icon class

// Import Font Icon Library
import './assets/fonts/iconfont.css'

Add Icon

<el-input prefix-icon="iconfont icon-user"></el-input>

The effect is shown in the diagram

  • Form Data Binding
    Objects in the data property can be bound in the element-ui form
    Bind the properties of the object in each input box
//Form Binding
<el-form :model="loginForm" label-width="0" class="login_form">
//Input Box Binding
<el-input v-model="loginForm.username" prefix-icon="iconfont icon-user"></el-input>
<el-input v-model="loginForm.password" prefix-icon="iconfont icon-3702mima"></el-input>
//Data in dta
data() {
  return {
      loginForm: {
          username: '',
          password: ''

Hide the data in the password box Add "type="password"to the input box

  • Data Form Validation

element-ui binds a rule validation rule to the form for data validation The validation rule is also declared in the data
Binding Validation Rules

 <el-form :rules="loginFormRules" :model="loginForm" label-width="0" class="login_form">
<!--        User name-->
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" prefix-icon="iconfont icon-user"></el-input>
<!--        Password-->
        <el-form-item prop="password">
          <el-input type="password" v-model="loginForm.password" prefix-icon="iconfont icon-3702mima"></el-input>

Claim Validation Rules

data() {
      return {
          // Form Validation Rules
          loginFormRules: {
              username: [
                  { required: true, message: 'enter one user name', trigger: 'blur' },
                  { min: 5, max: 10, message: 'Length between 5 and 10 characters', trigger: 'blur' }
              password: [
                  { required: true, message: 'enter one user name', trigger: 'blur' },
                  { min: 5, max: 10, message: 'Length between 5 and 10 characters', trigger: 'blur' }

Required: indicates whether it is required

message: indicates a prompt

trigger: indicates when to verify

min: for minimum length

max: for maximum length

  • Set Reset Button

element-ui provides the reSetfiled method in the form form form by simply getting the form's reference object
Can reset the form

Method Name Explain
resetFields Reset the entire form, reset all field values to their initial values, and remove the check results
<el-form ref="loginFormRef" :rules="loginFormRules" :model="loginForm" label-width="0" class="login_form">

The ref here is the reference object for the form

Bind click events for reset buttons

<el-button type="info" @click="resetLoginForm">Reset</el-button>

Declare in methods that clicking the event handler invokes the resetFields method that element-ui binds to the form's reference object

 methods: {
      // Click the Reset button to reset the form object
        resetLoginForm() {

This. $Refs.loginFormRefIs an instance object of the form

  • Prevalidation of forms

Similar to form resets, the validate method for which element-ui is bound is invoked through the form's reference object

Method Name Explain parameter
validate The method of checking the entire form with a callback function as the parameter.The callback function is called at the end of the check and passes in two parameters: whether the check succeeds or fails.If no callback function is passed in, a promise is returned Function(callback: Function(boolean, object))
  • Initiate login request through axios

First, still import axios into the entry file

//Import axios
import axios from 'axios'
//Set default root path
axios.defaults.baseURL = '';
//Mount axios on the vue prototype instance
Vue.prototype.$http = axios;

Direct return if pre-validation fails

Call axios method to initiate login request if pre-validation succeeds

Configure BoxTips

import { Message } from 'element-ui'
//Mount to Global
Vue.prototype.$message = Message;
// Logon function
        login() {
            this.$refs.loginFormRef.validate(async valid => {
                // console.log(valid);
                if(!valid) return;
                const { data: res } = await this.$http.post('login', this.loginForm);
                if(res.meta.status !== 200) return this.$message.error('Login failed!');
                this.$message.success('Landing success!');
                // Save the token value after successful login in sessionStorage(token should only take effect during the current site opening)
                window.sessionStorage.setItem("token", res.data.token);
                // Jump to Home Page by Programmatic Navigation
  • Set the Route Navigation Guard to determine whether to log in
// Hang on Route Navigation Guard
router.beforeEach((to, from, next) => {
  // To is the path to be visited
  // From represents the path from which
  // next for release
  if (to.path === '/login') return next();
  // Get token
  const tokenStr = window.sessionStorage.getItem('token');
  if (!tokenStr) return next('/login')

4 Exit

Exit Realization Principle

Exit based on token Simply destroy the local token and subsequent requests will not carry the token. The token must be logged in again to generate a token to access the page

  logout() {
            // Destroy token
            // Jump to the login page

Tags: Vue axios Session git

Posted on Sun, 14 Jun 2020 19:59:14 -0400 by hd_webdev