Consider this Vue 3 component using the Fetch API inside onMounted. What will be shown in the template after the component loads?
<script setup> import { ref, onMounted } from 'vue' const data = ref(null) onMounted(async () => { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1') data.value = await response.json() }) </script> <template> <div> <p v-if="data">Title: {{ data.title }}</p> <p v-else>Loading...</p> </div> </template>
Check how ref and await are used inside onMounted.
The component uses ref to create a reactive variable data. The onMounted hook fetches JSON data and assigns it to data.value. Once data is loaded, the template shows the title from the fetched object.
async setup()?Choose the correct code snippet that fetches JSON data inside the setup() function using async syntax.
Remember that await can only be used inside async functions.
Option A correctly marks setup as async, uses await to fetch and parse JSON, and returns a reactive data. Other options misuse await or do not handle reactivity properly.
Examine this Vue 3 component code. It fetches data but the template never updates to show the fetched title. What is the cause?
<script setup> import { ref, onMounted } from 'vue' const data = null onMounted(async () => { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1') data = await response.json() }) </script> <template> <div> <p v-if="data">Title: {{ data.title }}</p> <p v-else>Loading...</p> </div> </template>
Check how Vue tracks changes to variables for reactivity.
The variable data is a plain variable, not reactive. Vue does not detect changes to it, so the template does not update. Using ref(null) makes it reactive.
errorMessage after fetch failure in this Vue component?This Vue 3 component tries to fetch data but the URL is invalid. What will be the value of errorMessage after the fetch attempt?
<script setup> import { ref, onMounted } from 'vue' const data = ref(null) const errorMessage = ref('') onMounted(async () => { try { const response = await fetch('https://invalid.url') if (!response.ok) throw new Error('Network response was not ok') data.value = await response.json() } catch (error) { errorMessage.value = error.message } }) </script> <template> <div> <p v-if="errorMessage">Error: {{ errorMessage }}</p> <p v-else-if="data">Data loaded</p> <p v-else>Loading...</p> </div> </template>
Consider what error message the browser throws on network failure.
When the URL is invalid, the fetch API throws a TypeError with message "Failed to fetch". This message is caught and assigned to errorMessage.
Which reason best explains why calling fetch directly inside a Vue template expression is a bad idea?
Think about how Vue templates render and handle data.
Vue templates expect synchronous data to render. Fetch returns a Promise, which is asynchronous. Calling fetch in templates would cause errors or unexpected behavior because templates cannot wait for Promises.