Performance: Fetch API in Vue components
This affects page load speed and interaction responsiveness by controlling when and how data is fetched and rendered in Vue components.
import { ref, onMounted } from 'vue'; const cache = {}; export default { setup() { const data = ref(null); onMounted(async () => { if (cache['data']) { data.value = cache['data']; } else { const response = await fetch('https://api.example.com/data'); data.value = await response.json(); cache['data'] = data.value; } }); return { data }; } }
import { ref, onMounted } from 'vue'; export default { setup() { const data = ref(null); onMounted(async () => { const response = await fetch('https://api.example.com/data'); data.value = await response.json(); }); return { data }; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Fetch in onMounted with caching | Minimal reactive updates | Single reflow after data arrives | Single paint update | [OK] Good |
| Fetch in onMounted without caching | Reactive updates each mount | Reflow per mount | Paint per mount | [!] OK |
| Fetch in template expressions | Multiple fetch triggers | Multiple reflows per render | Multiple paints | [X] Bad |
| Synchronous fetch blocking UI | Blocks initial render | Blocks reflow | Blocks paint | [X] Bad |
<script setup> component to load data on mount?<script setup> code runs?import { ref, onMounted } from 'vue';
const data = ref(null);
const error = ref(null);
onMounted(async () => {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
data.value = await res.json();
console.log(data.value.title);
} catch (e) {
error.value = 'Failed to load';
console.log(error.value);
}
});<script setup> snippet that fetches data:import { ref, onMounted } from 'vue';
const data = ref(null);
const error = ref(null);
onMounted(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(json => data = json)
.catch(() => error.value = 'Error fetching');
});<script setup> code correctly implements fetch with loading and error states?Pass the test and this pattern moves unknown