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:
bashnpm install axios
or
bashyarn 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
- We use
refto create a reactive referenceuserinitialized tonull. - The
onMountedhook ensures data requests execute after component mounting. It is one of the Composition API's lifecycle hooks, analogous to Vue 2'smounted. - Within the
onMountedhook, we useaxios.getto send a GET request to the specified URL. - Upon successful response, we assign
response.datatouser, triggering UI updates to display new user information. - 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.