Home > Web Front-end > Vue.js > VUE3 Getting Started Tutorial: Using the Vue.js plug-in to encapsulate API interface requests

VUE3 Getting Started Tutorial: Using the Vue.js plug-in to encapsulate API interface requests

王林
Release: 2023-06-15 08:25:16
Original
1883 people have browsed it

Vue.js is one of the more popular front-end frameworks currently. Vue3 is the latest version of Vue.js, which provides simpler syntax and better performance. In the development of Vue.js, data requests are an essential part, and API interface requests are also one of the common tasks of programmers. This tutorial will introduce in detail how to use the Vue.js plug-in to encapsulate API interface requests.

What is Vue.js plug-in?

In Vue.js, a plug-in is a functional module that can provide global-level functions for Vue.js applications. We can encapsulate functionality in plugins and inject properties, directives, components, and more into Vue.js applications. Vue.js officially provides some common plug-ins for us to use, such as Vue Router and Vuex. Of course, we can also write our own plug-ins to achieve the functions we need.

  1. Creating plug-ins

We can create simple plug-ins by defining global functions or properties. But in this tutorial, we will introduce how to encapsulate API interface requests in a plug-in. First, we need to install axios, which is a popular JavaScript library for handling HTTP requests.

npm install axios --save

Then, we create an API plugin as follows:

import axios from 'axios'

const ApiPlugin = {
install(Vue) {

Vue.prototype.$api = {
  get(url) {
    return axios.get(url)
  },
  post(url, data) {
    return axios.post(url, data)
  }
}
Copy after login

}
}

export default ApiPlugin

In the above code, we define an ApiPlugin plug-in, It contains an install() method that accepts the Vue constructor as a parameter. A $api attribute is defined in the install() method, and an object containing two methods (get and post) is attached to Vue.prototype.

  1. Using Plugins

Now that we have created an API plugin, we need to use it in our Vue.js application. We can use the following code to introduce the plugin into the Vue.js application:

import Vue from 'vue'
import App from './App.vue'
import ApiPlugin from './ api-plugin'

Vue.use(ApiPlugin)

new Vue({
render: h => h(App),
}).$mount(' #app')

In the above code, we first introduce the ApiPlugin into the application through the import statement, and then use the Vue.use() method to install the plug-in. Finally, we create a Vue instance and mount it on the #app element. Now, we can use the $api attribute to make API requests in our application.

  1. Send API request

Suppose we want to send a GET request and get the returned data. We can use the $api.get() method in the Vue component to achieve this: