SoFunction
Updated on 2025-03-03

Code implementation for API data interaction using Vue3 and Axios

introduction

In modern web development, the use of front-end frameworks and libraries is becoming more and more common, and it is one of the popular choices. Through the Composition API and setup syntax sugar introduced by Vue 3, we can organize our code more flexibly and improve the readability and maintainability of our code. At the same time, Axios, as a Promise-based HTTP client, can help us easily interact with the API. In this blog, I will introduce how to use Vue 3 and Axios for API data interaction and demonstrate its basic usage through sample code.

1. Environmental preparation

Before you start, make sure you have installed and npm. Next, we can use the Vue CLI to create a new project. Open the terminal and execute the following command:

npm install -g @vue/cli
vue create vue-axios-example
cd vue-axios-example
npm install axios

At this point, we have created a new Vue project and installed the Axios module.

2. Component structure

In this example, we will create a simple component that will get some data from a public API (such as JSONPlaceholder) and display it on the page. We will create a new file in the src/components directory.

<template>
  <div>
    <h1>User List</h1>
    <ul v-if="">
      <li v-for="user in users" :key="">
        {{  }} - {{  }}
      </li>
    </ul>
    <p v-else>Loading users...</p>
    <button @click="fetchUsers">Refresh Users</button>
  </div>
</template>

<script>
import { ref } from 'vue';
import axios from 'axios';

export default {
  name: 'UserList',
  setup() {
    const users = ref([]);

    const fetchUsers = async () => {
      try {
        const response = await ('/users');
         = ;
      } catch (error) {
        ('Error fetching users:', error);
      }
    };

    // On component mount, fetch users
    fetchUsers();

    return {
      users,
      fetchUsers
    };
  },
};
</script>

<style scoped>
h1 {
  color: #42b983;
}
</style>

2.1 Component Analysis

  • Displays user data obtained from the API. If the data is still loading, the "Loading users..." prompt will be displayed.

  • Script section:exist<script>Part, we usesetupfunction. In this function we userefTo create a responsive variableusersand define asynchronous functionsfetchUsersto obtain user data.

    1. fetchUsersThe function uses Axios to send a GET request to obtain the user data of JSONPlaceholder.
    2. = Assign the obtained data tousers
  • Style section<style scoped>Make sure that the style only works on the current component.

3. Use components

To use our components in the application, we cansrc/The following modifications are made:

<template>
  <div >
    <UserList />
  </div>
</template>

<script>
import UserList from './components/';

export default {
  name: 'App',
  components: {
    UserList,
  },
};
</script>

<style>
#app {
  text-align: center;
  margin-top: 60px;
}
</style>

Here we first importUserListcomponent, then use it in the template. This way, we can see the user list in the main application.

4. Run the project

So far, our project is ready to be completed. Now we can run the development server to see the effects of our components:

npm run serve

Open the browser and accesshttp://localhost:8080, you will see a user list, and there is a "Refresh Users" button below. Click this button to re-get user data.

5. Exception handling

On the abovefetchUsersIn the functions, we have already involved simple error handling. If any error occurs during the request process, the developer will see the console output related error information. In order to further improve the user experience, we can add some error prompts to the UI.

ReviseState management in:

&lt;template&gt;
  &lt;div&gt;
    &lt;h1&gt;User List&lt;/h1&gt;
    &lt;ul v-if=""&gt;
      &lt;li v-for="user in users" :key=""&gt;
        {{  }} - {{  }}
      &lt;/li&gt;
    &lt;/ul&gt;
    &lt;p v-else-if="error"&gt;{{ error }}&lt;/p&gt;
    &lt;p v-else&gt;Loading users...&lt;/p&gt;
    &lt;button @click="fetchUsers"&gt;Refresh Users&lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import { ref } from 'vue';
import axios from 'axios';

export default {
  name: 'UserList',
  setup() {
    const users = ref([]);
    const error = ref(null);

    const fetchUsers = async () =&gt; {
       = null; // Clear error      try {
        const response = await ('/users');
         = ;
      } catch (err) {
         = 'Error fetching users: ' + ;
      }
    };

    fetchUsers();

    return { users, fetchUsers, error };
  },
};
&lt;/script&gt;

In this code, we introduce a new responsive variableerror, used to save error information and display it appropriately in the UI. In this way, when the user fails to obtain data, he can see relevant error prompts.

Summarize

Through this blog, we learned how to use Vue 3's setup syntax sugar and Axios for simple API data interaction. With these modern tools, we can manage front-end state and API requests more flexibly. Whether creating independent components or building complex applications, this approach can greatly improve our development efficiency and code quality.

The above is the detailed content of the code implementation of API data interaction using Vue3 and Axios. For more information about Vue3 Axios API data interaction, please follow my other related articles!