Performance: Fetch API in Vue components
MEDIUM IMPACT
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 |