SoFunction
Updated on 2025-04-13

Vue asynchronously requesting backend interface through axios

Axios in Vue

1. Install Axios

To use Axios in a Vue 3 project, you first need to install the Axios library. It can be installed via npm or yarn.

npm install axios

or

yarn add axios

After the installation is complete, the Axios library will be added to the node_modules directory of the project, and you can import and use it in the project.

2. Configure Axios instances

To simplify the use of Axios, you can create an Axios instance and configure it globally. This avoids repeated configuration of Axios in each component. A new file can be created in the project's src directory, for example.

// src/
import axios from 'axios';

const instance = ({
  baseURL: '', // Configure the basic URL  timeout: 1000, // Configure the request timeout time  headers: {'X-Custom-Header': 'foobar'} // Configure the default request header});

export default instance;

This creates an Axios instance with the default configuration, which can be imported and used directly in the project in the future.

3. Use Axios in Vue components

In Vue 3 components, HTTP requests can be initiated directly using configured Axios instances. Here is a simple example.

<template>
  <div>
    <h1>Data from API</h1>
    <ul>
      <li v-for="item in items" :key="">{{  }}</li>
    </ul>
  </div>
</template>

<script>
import axios from '../axios'; // Import the configured Axios instance
export default {
  data() {
    return {
      items: []
    };
  },
  mounted() {
    ();
  },
  methods: {
    async fetchData() {
      try {
        const response = await ('/items');
         = ;
      } catch (error) {
        ('Error fetching data:', error);
      }
    }
  }
};
</script>

In this example, the component is called when mountedfetchDataMethod, use Axios to initiate a GET request and store the returned data to the component'sitemsin data attributes.

4. Process Axios requests and responses

In practical applications, handling requests and responses is very important. To better handle these situations, an interceptor can be used. The interceptor can perform some global processing before the request is sent and after the response is received.

// src/
import axios from 'axios';

const instance = ({
  baseURL: '',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

// Add a request interceptor(function (config) {
  // What to do before sending a request  ('Request:', config);
  return config;
}, function (error) {
  // Processing request error  return (error);
});

// Add a response interceptor(function (response) {
  // Do something about the response data  ('Response:', response);
  return response;
}, function (error) {
  // Handle response errors  return (error);
});

export default instance;

By using an interceptor, requests and responses can be processed globally. For example, you can add an authentication token in the request interceptor, or handle error information uniformly in the response interceptor.

5. Actual case: User management function

Next, we will use an actual user management function case to show how to use Axios to perform CRUD (add, delete, modify and check) operations in Vue 3.

1. Create a user list component

existcomponentsCreate in folder, and add the following code:

<template>
  <div>
    <h1>User List</h1>
    <button @click="fetchUsers">Refresh user</button>
    <ul>
      <li v-for="user in users" :key="">
        {{  }} <button @click="deleteUser()">delete</button>
      </li>
    </ul>
    <input v-model="newUserName" placeholder="Enter new user name" />
    <button @click="addUser">Add a user</button>
  </div>
</template>

<script>
import axios from '../axios';

export default {
  data() {
    return {
      users: [],
      newUserName: ''
    };
  },
  methods: {
    async fetchUsers() {
      try {
        const response = await ('/users');
         = ;
      } catch (error) {
        ('Failed to get the user:', error);
      }
    },
    async addUser() {
      if (!) return;
      try {
        const response = await ('/users', {
          name: 
        });
        ();
         = '';
      } catch (error) {
        ('Add user failed:', error);
      }
    },
    async deleteUser(userId) {
      try {
        await (`/users/${userId}`);
         = (user =>  !== userId);
      } catch (error) {
        ('Delete user failed:', error);
      }
    }
  },
  mounted() {
    ();
  }
};
</script>

In this component, we define a user list, add user input boxes and buttons, and be able to delete users.

2. Create a Vue 3 project and configure routing

First, make sure that your development environment is already installed and Vue CLI. Next, you can create a new Vue 3 project:

vue create vue3-axios-crud

Select Vue 3 in the interactive prompt and go to the project directory:

cd vue3-axios-crud

Install Vue Router:

npm install vue-router@next

existsrcCreated in the directoryrouterfolder and adddocument:

// src/router/
import { createRouter, createWebHistory } from 'vue-router';
import UserList from '../components/';

const routes = [
  {
    path: '/',
    name: 'UserList',
    component: UserList
  }
];

const router = createRouter({
  history: createWebHistory(.BASE_URL),
  routes
});

export default router;

existsrc/Configure routing in:

// src/
import { createApp } from 'vue';
import App from './';
import router from './router';
import axios from './axios';

const app = createApp(App);
(router);
.$axios = axios; // Mount axios on global properties for easy use in components('#app');

3. Start the project

Run the following command from the command line to start the project:

npm run serve

Open a browser and accesshttp://localhost:8080, you should be able to see the user list and be able to add and delete users.

This is the article about Vue's method of asynchronously requesting backend interfaces through axios. For more related content on Vue axios requesting backend interfaces, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!