SoFunction
Updated on 2025-04-04

Implementation example of vue implementation interface encapsulation

Here is a simple interface encapsulation case:

  • Create a new oneFile, used to encapsulate interface requests:

    import axios from 'axios'
    
    // Create an axios instanceconst instance = ({
      // API address  baseURL: '/api/',
      // Timeout time  timeout: 10000
    })
    
    // Encapsulate GET requestfunction get(url, params) {
      return (url, { params })
    }
    
    // Encapsulate POST requestfunction post(url, data) {
      return (url, data)
    }
    
    // Export functionexport default {
      get,
      post
    }
    
  • Use encapsulated interface requests in Vue components:

    <template>
      <div>
        <h1>{{ message }}</h1>
      </div>
    </template>
    
    <script>
    import api from './api'
    
    export default {
      data() {
        return {
          message: ''
        }
      },
      created() {
        ('hello', { name: 'world' })
          .then(response => {
             = 
          })
          .catch(error => {
            (error)
          })
      }
    }
    </script>
    

In the above example,File encapsulatedget()andpost()Two functions for GET and POST requests. In Vue component, byimport api from './api'Introduce encapsulated request function and use()Start a GET request and pass in parameters. After the request is successful, the data returned by the request is passedGet it and assign it tomessageProperties, finally rendered in the template.

Using this packaging method can make the code more modular and convenient for maintenance and update. At the same time, it can also effectively decouple the front-end code and the back-end interface, making the code clearer and easier to understand.

This is the end of this article about the implementation example of vue implementation interface encapsulation. For more related vue interface encapsulation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!