Project login page Considerations and implementation (Vue)

Procedure 1 Create a login page and configure routes

1.1 Creating Components

Create a login folder in the SRC /views file, and login.vue in the login folder (you can create your own directory)

1.2 Configuring Routes

Open the index.js file in the Route folder and add a new route (the route addresses are configured according to the current directory address you created)

{
  path:'/login'.name:'login'.components:() = >import(/* webpackChunkName:"login" */ '@/views/login/login.vue)
}
Copy the code

Configure the routing container in app.vue

<template>
  <div id="app">
    <! -- Route exit -->
    <router-view></router-view>// Project initialization normally takes</div>
</template>
Copy the code

Style manipulation and form validation

2.1 Style Processing

Global import



insrcCreate one in the directorystylesFile, and inmain.jsIn the import

+ import '@/styles/index.less'
Copy the code

Local modification



scopedPrevent contamination of global styles

2.2 Form Verification

Don’t forget to validate forms when submitting user accounts and passwords using bidirectional binding to retrieve user input and regular expressions to filter validation of retrieved information

3 Axios encapsulates the obtained data

3.0 installation axios

npm i axios
Copy the code

3.1 Encapsulation and Import



insrcCreate a file in the directoryrequest.jsEncapsulate AXIos under this file

import axios from 'axios' / / introduction
// Create an axios instance and configure it
const request = axios.create({ // The request name can be customized
  baseURL:'Back end interface base address'
  // For example:baseURL:'http://localhost:8000'
})
export default request / / export
Copy the code

Where does it need to be called

4 Send an Ajax request for login

Encapsulate the user login method and invoke it in logn.vue

4.1 Encapsulation (Example)



A new call file is createdlogin.js

import request from '@/utils/request.js' // Import axios wrapped above
export const login = (user) = > {
  return request({
    url:' ' // Interface address
    method:' ' / / way
    // Use => data if the parameter is posted via the request body
    // If parameters are sent through the request body (GET), use => params
    data:user
  })
}
Copy the code

4.2 call

Called in login.vue

import {login} from '@/api/login/login.js'  / / introduction
export default {
  methods:{
    onSubmit () {
      this.doLogin() // Call doLogin when the user account password is submitted
    },
    async doLogin () {
      try{
        const res = await login (this.user)  // Call the wrapped axios method
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
Copy the code

4.3 check

View the effect in the console’s Network to see if the request was sent successfully

5 token processing

5.1 Functions and Usage process of the Token

  1. What the token does: It is a token that is generated by the back end and used to request interfaces that require permissions. If the token is not included, an error occurs

2. Basic usage process

(1) The user logs in and obtains the token

(2) Save the token locally

(3) Carry tokens when making other requests

5.2 Example for Obtaining User Information (You need to carry a token to obtain user Information; otherwise, an error message will be displayed)

5.2.1 Adding a Method Call Interface



createuser.js

import request from '@/utils/request.js'

export const getUserInfo = () = > {
  return request({
    method: ' './ / way
    url: ' ' // Interface address})}Copy the code

5.2.2 Save tokens in Vuex

Get the token (the above login example encapsulates axios and modifs it with the above login example), get the token in the store/index.js file and save it

import { login } from '.. /api/login/login'
export default new Vuex.Store({
  state: {
    tokenInfo: {} // Save the token
  },
  mutations: {
    setTokenInfo (state, newTokenInfo) {
      state.tokenInfo = newTokenInfo // Change the token value in state to tokenInfo in state}},actions: {
    async userLogin (context, userinfo) {  / / access token
      try {
        const res = await login(userinfo)
        console.log(res)
        // res,data.data is the token to find the obtained RES data. Each interface calls different data, so you can use console.log output to find the desired data
        context.commit('setTokenInfo', res.data.data)  // Call the mutations method setTokenInfo
      } catch (err) {
        throw new Error(err)
      }
    }
  }
})
Copy the code

Modifying loginlogin.vueYou just need to call the actions method in Vuex

export default {
  methods:{
    onSubmit () {
      this.doLogin()
    },
    async doLogin () {
      try{
        await this.$store.dispatch('userLogin'.this.user)
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
Copy the code

Finally, check whether tokenInfo is obtained, click login, and check in the console

5.2.3 Adding a Token to a Request Interceptor

Request interceptor: All AXIos requests go through the request interceptor

utils/request,jsTo add interceptors

request.interceptors.request.use(function (config) {
  const token = store.state.tokenInfo.token TokenInfo = tokenInfo = tokenInfo = tokenInfo = tokenInfo = tokenInfo = tokenInfo
  if (token) { // Verify that the token exists. If so, add the token to headers
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function (error) {
  return Promise.reject(error)
})
Copy the code

5.2.4 Saving User Information to VUex

Since the user information needs to be used in different components, it is stored in the Store repository. If you are afraid of too much code, you can separate modules to write, create the modules folder in the store, and then create the user.js file, which is written exactly the same as the store



inuser.jsIn the call5.2.1Set ingetUserInfoInterface method to obtain user information

import { getUserInfo } from '.. /.. /api/user'

export default {
  namespaced: true.state: {
    userInfo: {} // Get user data
  },
  mutations: {
    setUserInofo (state, userInfo) { // Change the data in state after the latest user data is obtained
      state.userInfo = userInfo
    }
  },
  actions: {
    async getUserInfo (context) {
      try {
        const res = await getUserInfo()
        console.log(res)
        // res,data.data is the token to find the obtained RES data. Each interface calls different data, so you can use console.log output to find the desired data
        context.commit('setUserInofo', res.data.data)
      } catch (err) {
        throw new Error(err)
      }
    }
  }
}
Copy the code

Add modules to store/index.js and call user.js

import user from './modules/user'
modules: {
    user
  }
Copy the code

Finally, inlogin.vueIf you want to get the token, you can call the actionstore/index.jsIn theactions, so you don’t need to write the module name when calling

5.2.5 Verify whether the token is saved and the user data is obtained

token

The user information