π Vue HTTP Requests β Interacting with APIs in Vue 3 (2025 Guide)
π§² Introduction β Why Are HTTP Requests Important in Vue?
In modern Vue applications, HTTP requests are essential for fetching data from APIs, sending form submissions, and integrating with backend services. Vue doesn’t ship with an HTTP client, but it’s commonly paired with libraries like Axios or the Fetch API to perform these operations.
π― In this guide, youβll learn:
- How to make GET, POST, PUT, DELETE requests in Vue
- The difference between Fetch API and Axios
- How to manage API responses, errors, and loading states
- Real-world examples with full code and output
π Popular HTTP Clients in Vue
Client | Description | Vue Compatibility |
---|---|---|
Axios | Promise-based, supports interceptors | β Recommended |
Fetch API | Built-in browser API | β Supported |
π Installing Axios (Optional)
npm install axios
Then import it in your component:
import axios from 'axios';
π§± Example 1 β Basic GET Request (Axios)
β Fetching Posts from an API
<template>
<div>
<h2>Posts</h2>
<ul v-if="posts.length">
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
<p v-else>Loading...</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return { posts: [] };
},
created() {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
this.posts = response.data.slice(0, 5); // limit to 5
})
.catch(error => {
console.error('Error fetching posts:', error);
});
}
}
</script>
π§ This component loads data when created and updates the view.
π¬ Example 2 β POST Request (Axios)
β Submitting a Form
<template>
<form @submit.prevent="submitForm">
<input v-model="title" placeholder="Title" />
<button type="submit">Submit</button>
</form>
</template>
<script>
import axios from 'axios';
export default {
data() {
return { title: '' };
},
methods: {
submitForm() {
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: this.title,
body: 'Sample Body',
userId: 1
})
.then(res => console.log('Post created:', res.data))
.catch(err => console.error('Error:', err));
}
}
}
</script>
π§ @submit.prevent
prevents page reload and sends the POST request.
π PUT / DELETE Requests
β Update (PUT)
axios.put('/api/item/1', {
title: 'Updated Title'
});
β Delete
axios.delete('/api/item/1');
β οΈ Handling Errors & Loading State
β Pattern:
data() {
return {
posts: [],
loading: false,
error: null
}
},
created() {
this.loading = true;
axios.get('/api/posts')
.then(res => this.posts = res.data)
.catch(err => this.error = err.message)
.finally(() => this.loading = false);
}
π§ This improves UX by showing loaders or errors based on request states.
𧬠Using Fetch API Instead of Axios
β Example:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => this.posts = data)
.catch(error => console.error(error));
π§ Fetch is native and lightweight but lacks interceptors and automatic JSON parsing for errors.
π Real-World Use Case β Auth Token in Header
β Using Axios Interceptors:
axios.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
return config;
});
π Summary β Recap & Next Steps
Vue apps often rely on HTTP requests to interact with backend services. With Axios or Fetch, Vue makes it easy to integrate APIs for data-driven UIs.
π Key Takeaways:
- Use Axios for robust HTTP features like interceptors
- Use Fetch for native support and simplicity
- Handle loading and error states properly
- Use lifecycle hooks like
created()
to trigger API calls
βοΈ Real-World Relevance:
Essential for SPAs that rely on APIsβe.g., dashboards, forms, content feeds, admin panels.
β FAQ Section
β How do I send a GET request in Vue?
β Use Axios or Fetch in lifecycle hooks:
axios.get('/api/posts')
β Should I use Axios or Fetch in Vue?
β Axios is preferred for complex apps. Fetch is fine for basic use cases.
β How do I handle request errors in Vue?
β
Use .catch()
or try...catch
with async/await
.
β Where should I call the API in a Vue component?
β
Inside created()
or mounted()
lifecycle hooks.
β How do I show loading while the request is in progress?
β
Track loading
in data()
and use conditional rendering.
Share Now :