The Fetch API lets your Vue component get data from the internet easily. It helps your app show fresh information without reloading the page.
Fetch API in Vue components
fetch(url) .then(response => response.json()) .then(data => { // use the data here }) .catch(error => { // handle errors here })
The fetch function returns a promise that resolves to a response object.
You usually call response.json() to get the data in JSON format.
fetch('https://api.example.com/data') .then(res => res.json()) .then(data => console.log(data))
fetch('https://api.example.com/data') .then(res => { if (!res.ok) throw new Error('Network error') return res.json() }) .then(data => console.log(data)) .catch(err => console.error(err))
This Vue component fetches user data from a public API when it loads. It shows a loading message while waiting, displays the user name and email when done, and shows an error message if something goes wrong. It uses semantic HTML and ARIA roles for accessibility.
<template>
<main>
<h1>User Info</h1>
<section aria-live="polite">
<p v-if="loading">Loading user data...</p>
<p v-if="error" role="alert" style="color: var(--error-color);">Error: {{ error }}</p>
<article v-if="user">
<h2>{{ user.name }}</h2>
<p>Email: {{ user.email }}</p>
</article>
</section>
</main>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const user = ref(null)
const loading = ref(false)
const error = ref(null)
onMounted(async () => {
loading.value = true
error.value = null
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1')
if (!response.ok) throw new Error('Failed to fetch user data')
user.value = await response.json()
} catch (err) {
error.value = err.message
} finally {
loading.value = false
}
})
</script>
<style scoped>
:root {
--error-color: #b00020;
}
main {
max-width: 30rem;
margin: 2rem auto;
font-family: Arial, sans-serif;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 0.5rem;
}
article {
background-color: #f9f9f9;
padding: 1rem;
border-radius: 0.25rem;
}
</style>Always handle errors to avoid your app breaking if the fetch fails.
Use aria-live="polite" to announce loading or error messages to screen readers.
Keep your UI responsive by showing loading states while waiting for data.
The Fetch API helps your Vue app get data from the internet easily.
Use fetch inside lifecycle hooks like onMounted to load data when the component appears.
Show loading and error messages to keep users informed.