Performance: GET requests in components
This affects page load speed and interaction responsiveness by controlling when and how data is fetched and rendered in Vue components.
<script setup> import { ref } from 'vue'; const data = ref(null); // Fetch data outside component or use server-side fetching fetch('https://api.example.com/data') .then(res => res.json()) .then(json => data.value = json); </script> <template> <div v-if="data">{{ data }}</div> <div v-else>Loading...</div> </template>
<script setup> import { onMounted, ref } from 'vue'; const data = ref(null); onMounted(async () => { const response = await fetch('https://api.example.com/data'); data.value = await response.json(); }); </script> <template> <div>{{ data }}</div> </template>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fetch in onMounted (after initial render) | Minimal DOM nodes initially | Triggers 1 reflow after data arrives | Paint delayed until data ready | [X] Bad |
| Fetch outside component with loading state | More DOM nodes for loading UI | Single reflow when data replaces loading | Paint happens immediately with loading | [OK] Good |
onMounted.onMounted(() => { ... }).<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);
});{ "message": "Hello Vue" }.response.json() parses it into an object.message key with value "Hello Vue", so console.log(data.message) prints "Hello Vue".<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);
});response is a Promise, not the actual response.response.json() on a Promise causes data to be a Promise too, so logging it shows a Promise object, not data.<script setup> code correctly handles loading, success, and error states for a GET request?ref for user, loading, and error, properly reactive for Vue.Pass the test and this pattern moves unknown