This is the 6th day of my participation in the August More Text Challenge

Request to send

  • Introduce the previously encapsulated request module Request
  • Send the request when it commits
    • Handle asynchronous operations with async and await

    What is Promise?

// Process the validation result
    async onSubmit () {
      try {
        // 1. Form validation
        await this.$refs.form.validate()
        // 2. Request to invoke the request module
        request({
          method: 'POST'.url: '/front/user/login'.data: {
            phone: this.form.phone,
            password: this.form.password
          }
        })
        // 3. Response processing
      } catch (err) {
        console.log('Verification failed', err)
      }
    }
Copy the code
  • Request parameter processing failed: Since axios request parameters default to Application/JSON format, the interface requires X-www-form-urlencoded format.

    • Console View the error message returned by the backend

    • The console looks at the send data and request header information

  • Add: Urlencoded format -> name = value & name = value

  • Solution: Manual more troublesome, can use the module processing

    • Convert the AXIos request parameter format based on the interface needs, as you can see in the AXIOS documentation. The QS module is used for processing. First, install the QS module through NPM
    • The implementation code
      // Process the validation result
        async onSubmit () {
          try {
            // 1. Form validation
            await this.$refs.form.validate()
            // 2. Request to invoke the request module
            request({
              method: 'POST'.// Header can be omitted and qs.stringify will be set automatically
              url: '/front/user/login'.// Convert to urlencoded format
              data: qs.stringify(this.form)
            })
            // 3. Response processing
          } catch (err) {
            console.log('Verification failed', err)
          }
        }
      Copy the code
    • Use of QS Module
  • Tip: In order to facilitate the test, you can set the data in the data as the test phone and password to simplify the operation.

Request Result processing

  • According to the user-defined status code provided in the interface document, all the status codes except 1 or 200 are successful.
    • If successful, jump to background home /home –this.$router.push()
    • Failure prompts
  • The actual code
// 3. Response processing
// Failure prompt
if(data.status ! = =1) {
  return alert(data.message)
}
// Go to the home page on success
this.$router.push({
  name: 'home'
})
Copy the code
  • Error beautification is done through Element’s Message prompt component
    • In addition to providing components, Element also provides methods for Vue instances that trigger functionality
    • Use message.error() and message.error() with message.error() and message.success() in the Message component
  • The actual code
// 3. Response processing
// Failure prompt
if(data.status ! = =1) {
  return this.$message.error(data.message)
}
// Go to the home page on success
this.$router.push({
  name: 'home'
})
this.$message.success(data.message)
Copy the code

Avoid repeated requests

  • When the request speed is slow (slow network speed), clicking the login button multiple times will cause the request to be triggered repeatedly, which is meaningless

  • The solution

    • Disable login button click events during the request, set variables to Boolean control
    • This can be done through the “loading” function of the Button component in Element
  • The actual code

// Process the validation result
    async onSubmit () {
      try {
        // 1. Form validation
        await this.$refs.form.validate()
        // 2. Request to invoke the request module
        // Setup button loading before sending request
        this.isLoginLoading = true
        const { data } = await request({})
        // Cancel the loading state
        this.isLoginLoading = false
        // 3. Response processing
      } catch (err) {
        console.log('Verification failed', err)
      }
    }
Copy the code

Encapsulating request method

  • Create user.js in the service directory to encapsulate the functional modules requested by the user
  • Encapsulates requests for user login interfaces
// Encapsulate the user request module
import request from '@/utils/request'
import qs from 'qs'

// data Indicates the data to be passed
export const login = data= > {
    return request({
      method: 'POST'.// Header can be omitted and qs.stringify will be set automatically
      url: '/front/user/login'.// Convert to urlencoded format
      data: qs.stringify(data)
    })
}
Copy the code
  • Introduce a wrapper module and invoke a method on the login page
// Introduce the encapsulation user login request module
import { login } from '@/services/user'
export default {
  // Export the configuration object of the current component
  name: 'LoginIndex',
  data () {},
  methods: {
    // Process the validation result
    async onSubmit () {
      try {
        // 1. Form validation
        await this.$refs.form.validate()
        // 2. Request to invoke the request module
        this.isLoginLoading = true
        // Replace it with a method call and pass in data
        const { data } = await login(this.form)
        this.isLoginLoading = false
        // 3. Response processing
      } catch (err) {
        console.log('Verification failed', err)
      }
    }
  }
}
Copy the code
  • After the test is successful, encapsulate all interface requests in the module