Using Axios to make requests in Vue Composition API typically involves several steps: installing Axios, setting up reactive data, creating a request function, and calling it in the appropriate lifecycle hook.
Here is a specific example demonstrating how to make a GET request using Axios in Vue Composition API:
First, ensure Axios is installed. If not, install it using npm or yarn:
shnpm install axios # or yarn add axios
Next, you can define reactive data and methods in a Vue component using the setup function. Here is an example:
javascript<template> <div> <div v-if="error">Request failed: {{ error }}</div> <div v-else-if="data"> <!-- Display your data here --> <div>{{ data.title }}</div> </div> <div v-else>Loading...</div> </div> </template> <script> import { ref, onMounted } from 'vue'; import axios from 'axios'; export default { setup() { const data = ref(null); // Stores the response data const error = ref(null); // Stores potential error messages const loading = ref(false); // Indicates if a request is in progress // Define the request function const fetchData = async () => { loading.value = true; error.value = null; // Reset error on each request try { const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1'); data.value = response.data; // Update data on success } catch (e) { error.value = e.message; // Update error on failure } finally { loading.value = false; // Update loading state after request } }; // Call the function after component mounts onMounted(() => { fetchData(); }); // Expose reactive variables to the template return { data, error, loading }; } };
In the above example, we first define three reactive variables: data for storing the requested data, error for storing potential error messages, and loading for indicating whether a request is in progress. Then, we define an asynchronous function named fetchData responsible for making a GET request using Axios. This function is called in the onMounted lifecycle hook to ensure data requests are initiated immediately after the component mounts. Finally, we expose the reactive variables via the return value of the setup function to the template for data binding and displaying status information.
This covers the basic process and example of using Axios to make requests in Vue Composition API.