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.
Practice
Solution
Step 1: Understand GET request purpose
A GET request is used to retrieve or fetch data from a server.Step 2: Relate to Vue component usage
In Vue components, GET requests are used to get data to show in the UI.Final Answer:
To fetch data from a server to display in the component -> Option CQuick Check:
GET request = fetch data [OK]
- Confusing GET with POST (sending data)
- Thinking GET updates local state only
- Mixing GET with delete operations
Solution
Step 1: Identify correct lifecycle hook name
The correct Vue 3 lifecycle hook to run code after component mounts isonMounted.Step 2: Confirm import and usage syntax
You import it from 'vue' and call it with a function:onMounted(() => { ... }).Final Answer:
import { onMounted } from 'vue'; onMounted(() => { /* fetch code */ }); -> Option DQuick Check:
Use onMounted for post-mount code [OK]
- Using wrong hook names like mounted or onLoad
- Forgetting to import onMounted
- Calling lifecycle hooks incorrectly
<script setup> snippet, what will be logged to the console after the component mounts?import { onMounted } from 'vue';
onMounted(async () => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data.message);
});Assuming the server responds with
{ "message": "Hello Vue" }.Solution
Step 1: Understand fetch and JSON parsing
The fetch call gets the response, andresponse.json()parses it into an object.Step 2: Access the message property
The parsed object has amessagekey with value "Hello Vue", soconsole.log(data.message)prints "Hello Vue".Final Answer:
"Hello Vue" -> Option BQuick Check:
Fetch JSON message logs "Hello Vue" [OK]
- Forgetting to await response.json()
- Logging response instead of parsed data
- Expecting syntax errors from correct async code
<script setup> code that tries to fetch data on mount?import { onMounted } from 'vue';
onMounted(() => {
const response = fetch('https://api.example.com/data');
const data = response.json();
console.log(data);
});Solution
Step 1: Identify async usage problem
fetch returns a Promise, soresponseis a Promise, not the actual response.Step 2: Explain consequence of missing await
Callingresponse.json()on a Promise causesdatato be a Promise too, so logging it shows a Promise object, not data.Final Answer:
Missing async/await causing response and data to be Promises -> Option AQuick Check:
Always await fetch and json() [OK]
- Not marking onMounted callback async
- Not awaiting fetch and json() calls
- Expecting immediate data without Promises
<script setup> code correctly handles loading, success, and error states for a GET request?Solution
Step 1: Check reactive state setup
import { ref, onMounted } from 'vue'; const user = ref(null); const loading = ref(true); const error = ref(null); onMounted(async () => { try { const res = await fetch('https://api.example.com/user'); if (!res.ok) throw new Error('Fetch failed'); user.value = await res.json(); } catch (e) { error.value = e.message; } finally { loading.value = false; } }); usesreffor user, loading, and error, properly reactive for Vue.Step 2: Verify async fetch with error handling
import { ref, onMounted } from 'vue'; const user = ref(null); const loading = ref(true); const error = ref(null); onMounted(async () => { try { const res = await fetch('https://api.example.com/user'); if (!res.ok) throw new Error('Fetch failed'); user.value = await res.json(); } catch (e) { error.value = e.message; } finally { loading.value = false; } }); uses async/await with try/catch/finally to handle success, errors, and loading state correctly.Final Answer:
Option A correctly manages loading, success, and error states with reactive refs and proper async handling. -> Option AQuick Check:
Use refs + async try/catch/finally for GET with states [OK]
- Not using reactive refs for loading and error
- Setting loading false too early or outside async flow
- Ignoring error handling in fetch
Ready to prove it?
Pass the test and this pattern moves unknown
