GET requests let your component ask a server for data. This helps your app show fresh information from the internet.
GET requests in components in Vue
<script setup> import { ref, onMounted } from 'vue' const data = ref(null) const error = ref(null) onMounted(async () => { try { const response = await fetch('https://api.example.com/data') if (!response.ok) throw new Error('Network error') data.value = await response.json() } catch (err) { error.value = err.message } }) </script>
Use onMounted to run the GET request when the component appears on screen.
Use ref to store the data and any error so the template can react to changes.
users.<script setup> import { ref, onMounted } from 'vue' const users = ref([]) onMounted(async () => { const res = await fetch('https://jsonplaceholder.typicode.com/users') users.value = await res.json() }) </script>
<script setup> import { ref, onMounted } from 'vue' const post = ref(null) const error = ref(null) onMounted(async () => { try { const res = await fetch('https://jsonplaceholder.typicode.com/posts/1') if (!res.ok) throw new Error('Failed to load post') post.value = await res.json() } catch (e) { error.value = e.message } }) </script>
This Vue component fetches a list of users when it loads. It shows a loading message while waiting, lists users when ready, and shows an error if the request fails.
<template> <section aria-label="User list"> <h2>Users</h2> <div v-if="error" role="alert" style="color: red">Error: {{ error }}</div> <ul v-else-if="users.length"> <li v-for="user in users" :key="user.id"> <strong>{{ user.name }}</strong> - {{ user.email }} </li> </ul> <p v-else>Loading users...</p> </section> </template> <script setup> import { ref, onMounted } from 'vue' const users = ref([]) const error = ref(null) onMounted(async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/users') if (!response.ok) throw new Error('Network response was not ok') users.value = await response.json() } catch (err) { error.value = err.message } }) </script>
Always handle errors to avoid your app breaking if the server is down or the URL is wrong.
Use semantic HTML and ARIA roles for accessibility, like aria-label and role="alert" for error messages.
Show a loading message so users know data is coming.
GET requests fetch data from servers to show in your component.
Use onMounted and fetch with async/await inside Vue's <script setup>.
Handle loading, success, and error states for a good user experience.