Imagine you want your Vue app to show weather data from an online service. Why is using an API important here?
Think about how your app can show new information without updating the app itself.
APIs allow Vue apps to fetch and show live data from other services, keeping the app lightweight and dynamic.
Look at this Vue component snippet that fetches user info from an API. What will the component show after the data loads?
<script setup> import { ref, onMounted } from 'vue' const user = ref(null) onMounted(async () => { const res = await fetch('https://api.example.com/user/1') user.value = await res.json() }) </script> <template> <div> <p v-if="user">Name: {{ user.name }}</p> <p v-else>Loading...</p> </div> </template>
Think about what happens before and after the API call finishes.
The component starts with user as null, so it shows 'Loading...'. After the API call completes, user is set and the name displays.
Choose the code snippet that properly catches errors when fetching API data inside a Vue component.
<script setup> import { ref, onMounted } from 'vue' const data = ref(null) const error = ref(null) onMounted(async () => { try { const res = await fetch('https://api.example.com/data') if (!res.ok) throw new Error('Network error') data.value = await res.json() } catch (e) { error.value = e.message } }) </script> <template> <div> <p v-if="error">Error: {{ error }}</p> <p v-else-if="data">Data loaded</p> <p v-else>Loading...</p> </div> </template>
Look for code that checks the HTTP response status and catches errors properly.
Option C checks if the response is OK before parsing JSON and catches errors with a try-catch block, providing clear error handling.
Consider this Vue code fetching a list of items and filtering them. What will be the value of items.value after the API call?
<script setup> import { ref, onMounted } from 'vue' const items = ref([]) onMounted(async () => { const res = await fetch('https://api.example.com/items') const data = await res.json() items.value = data.filter(item => item.active) }) </script>
Think about what filter does to the array.
The filter keeps only items where active is true, so items.value contains only those.
Examine this Vue code snippet. It tries to fetch user data but crashes with 'TypeError: Cannot read property 'name' of null'. Why?
<script setup> import { ref, onMounted } from 'vue' const user = ref(null) onMounted(async () => { const res = await fetch('https://api.example.com/user/1') user.value = await res.json() }) </script> <template> <div> <p v-if="user">Name: {{ user.name }}</p> </div> </template>
Check what happens before the API call finishes and how the template uses 'user'.
The template tries to read 'user.name' immediately, but 'user' starts as null. Accessing 'name' on null causes the TypeError.