0
0
Vueframework~5 mins

Fetch API in Vue components

Choose your learning style9 modes available
Introduction

The Fetch API lets your Vue component get data from the internet easily. It helps your app show fresh information without reloading the page.

When you want to load user info from a server after the page opens.
To get a list of products from an online store API and show them.
When you need to send data to a server after a form is submitted.
To update your app with live weather data from a public API.
When you want to fetch images or content dynamically based on user actions.
Syntax
Vue
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.

Examples
Fetch data from a URL and print it in the console.
Vue
fetch('https://api.example.com/data')
  .then(res => res.json())
  .then(data => console.log(data))
Fetch with error checking and handling.
Vue
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))
Sample Program

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.

Vue
<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>
OutputSuccess
Important Notes

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.

Summary

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.