Vue login function implementation

Vue login function implementation

Written in front

The vue file needs to have a blank line at the end, otherwise it will report an error, which is really weird...

Login Overview

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

Related technical points of login service

HTTP is stateless. It records the status on the client side through cookies, records the status on the server side through sessions, and maintains the status through tokens.

Please be clear here!

Login-token principle analysis

1. Enter your username and password on the login page to log in

2. After the server verifies the user, it generates a token and returns it

3. The client stores the token

4. All subsequent requests will carry this token to send the request

5. The server verifies whether the token is passed

Login function implementation

Login page layout

Implementing layout through Element-UI components

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

Open the terminal in vscode ctrl+~

git status View the current git status
git checkout -b login creates a new branch called login
git branch switch branch

insert image description here

Launch in vue-ui!

insert image description here

The terminal command npm run serve also works!

Create a vue file under the components file

import Vue from 'vue'
import VueRouter from 'vue-router'
import login from './components/login.vue'
Vue.use(VueRouter)

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

const router = new VueRouter({
  routes
})

export default router

Configure routing (and add routing redirects)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: login
    }
  ]
})

Be sure to pay attention to the spaces, otherwise it will report an error, damn!

Page Writing

First give a global style sheet

/* Global style sheet */
html,
body,
#app{
    height: 100%;
    margin: 0;
    padding: 0;
}

And import it in main.js

import './assets/css/global.css'

Complete login box center

Note: translate is used to move the cursor to achieve true centering.

.login_box{
    width: 450px;
    height: 300px;
    background-color: #fff;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

insert image description here

Add a login icon

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

insert image description here

Login form layout

Implementing layout through Element-UI components

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

Elements component library webpage can find some basic template codes that can be used in the website

Importing Components

import Vue from 'vue'
import { Button, Form, FormItem, Input } from 'element-ui'//Separate imports will result in an error Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)

The middle form and button are directly found in the component library above

I won’t post some of the code in the middle because it’s quite boring.

In particular, our small icons are downloaded from Alibaba's icon library

For specific usage, please refer to a blog I wrote before: Alibaba Icon Icons are under your control (how to introduce icon library in the front end, beautiful icons are at your disposal TT)

insert image description here

Data Binding for Login Form

1.:model="loginForm" binds a form

2. Use v-model to two-way bind data objects in form-item

3. In export default, data() returns form data

Validation rules for the login form

1.: rules="ruleForm" binds a rule

2. In form-item, use the prop attribute to set the field name that needs to be verified

      // This is the form validation rule object loginFormRules: {
        // Verify that the username is legal username: [
          { required: true, message: 'Please enter your login name', trigger: 'blur' },
          { min: 3, max: 10, message: 'Length is between 3 and 10 characters', trigger: 'blur' }
        ],
        // Verify that the password is valid password: [
          { required: true, message: 'Please enter your login password', trigger: 'blur' },
          { min: 6, max: 15, message: 'Length is between 6 and 15 characters', trigger: 'blur' }
        ]

      }

insert image description here

Resetting the login form

1. Add a ref reference name in el-form to get the form

2. Add a method in the method and use this.$refs.loginFormRef.resetFields() to reset the form. Note that the value of the form will become the initial value set in data

Login pre-authentication

1. The same this.$refs.loginFormRef.validate()

2. Configure axios

import axios from 'axios'
// Configure the root path of the request axios.defaults.baseURL = 'https://127.0.0.1:8888/api/private/v1/'
Vue.prototype.$http = axios

3. Get the query results as follows: Use async and await to get the returned results

      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('login', this.loginForm)
        console.log(res)
        if (res.meta.status !== 200) return console.log('Login failed')
        console.log('Login successful')
      })

Login component configuration pop-up prompt

1. Introduce message in element.js and mount it on vue

Vue.prototype.$message = Message // Mounted on Vue

2. Directly call this.$message.error('Login failed!')

insert image description here

Behavior after successful login

1. Save the token after login to the client's sessionStorage

1. Other API interfaces in the project, except for login, must be accessed after login

2. The token should only be valid while the current website is open, so save the token in sessionStorage

The token is stored in Session storage

insert image description here

2. Jump to the backend homepage through programmatic navigation, the routing address is /home

        window.sessionStorage.setItem('token', 'res.data.token')//Save token This is a fixed value that is saved randomly this.$router.push('/home') //Jump to the next page

This is the end of this article about the implementation of the Vue login function. For more relevant Vue login content, 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 keeps the user logged in (various token storage methods)
  • Vue implements user login and token verification
  • VUE implements token login verification
  • vue+springboot realizes login function
  • Vue implements login verification code
  • vue+springboot realizes login verification code
  • Springboot+vue realizes login function

<<:  Mysql join table and id auto-increment example analysis

>>:  Some suggestions for Linux system optimization (kernel optimization)

Recommend

MySQL 8.0.11 installation summary tutorial diagram

Installation environment: CAT /etc/os-release Vie...

Share 5 helpful CSS selectors to enrich your CSS experience

With a lot of CSS experience as a web designer, we...

Basic JSON Operation Guide in MySQL 5.7

Preface Because of project needs, the storage fie...

Add a copy code button code to the website code block pre tag

Referring to other more professional blog systems...

Analysis of parameter transfer process of driver module in Linux

Declare the parameter name, type and permission y...

Nginx monitoring issues under Linux

nginx installation Ensure that the virtual machin...

MySQL explain obtains query instruction information principle and example

explain is used to obtain query execution plan in...

17 404 Pages You'll Want to Experience

How can we say that we should avoid 404? The reas...

Vue3 gets the current routing address

Correct answer Using useRouter : // router path: ...