乐闻世界logo
搜索文章和话题

How to use Axios with Vue 3 Composition API

1个答案

1

Why Use Axios with Vue 3 Composition API

Axios is a Promise-based HTTP client for browsers and Node.js, enabling asynchronous HTTP requests to REST endpoints. Vue 3's Composition API provides a new approach to organizing and reusing logic, particularly for components with complex logic, resulting in clearer and more maintainable code.

How to Integrate

Using Axios with Vue 3's Composition API primarily involves creating and managing API requests within the setup() function. The following is a basic example demonstrating how to use Axios to send requests and handle responses in a Vue 3 component.

Step 1: Install Axios

First, if Axios is not already installed in your project, install it using npm or yarn:

bash
npm install axios

or

bash
yarn add axios

Step 2: Create a Vue 3 Component

Create a new Vue 3 component and import Axios along with reactive or ref from Vue for managing state.

vue
<template> <div> <h1>User Information</h1> <div v-if="user"> <p>Name: {{ user.name }}</p> <p>Email: {{ user.email }}</p> </div> <div v-else> <p>Loading...</p> </div> </div> </template> <script> import axios from 'axios'; import { ref, onMounted } from 'vue'; export default { setup() { const user = ref(null); onMounted(async () => { try { const response = await axios.get('https://api.example.com/user/1'); user.value = response.data; } catch (error) { console.error('Failed to fetch user data:', error); } }); return { user }; } }; </script>

Explanation

  1. We use ref to create a reactive reference user initialized to null.
  2. The onMounted hook ensures data requests execute after component mounting. It is one of the Composition API's lifecycle hooks, analogous to Vue 2's mounted.
  3. Within the onMounted hook, we use axios.get to send a GET request to the specified URL.
  4. Upon successful response, we assign response.data to user, triggering UI updates to display new user information.
  5. If the request fails, we log the error to the console.

Summary

Integrating Axios with Vue 3's Composition API effectively manages asynchronous API data while maintaining component clarity and efficiency. This approach enables easy reuse and maintenance of data fetching logic across any component.

2024年11月20日 22:56 回复

你的答案