Performance: Why API integration matters
API integration affects page load speed and interaction responsiveness by controlling how and when data is fetched and rendered.
<script setup> import { ref, onMounted } from 'vue'; const items = ref([]); onMounted(async () => { const response = await fetch('https://api.example.com/data'); items.value = await response.json(); }); </script>
export default { data() { return { items: [] }; }, created() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/data', false); xhr.send(); this.items = JSON.parse(xhr.responseText); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous XHR in created hook | Multiple updates after data arrives | Triggers 2-3 reflows | High paint cost due to blocking | [X] Bad |
| Asynchronous fetch in onMounted with ref | Single update after data arrives | Single reflow | Low paint cost, non-blocking | [OK] Good |
onMounted?data.value, which is correct for Vue refs.message after mounting?const message = ref('');
onMounted(async () => {
try {
const res = await fetch('/api/greet');
const data = await res.json();
message.value = data.text;
} catch {
message.value = 'Error loading';
}
});{ "text": "Hello Vue!" } successfully.data.text is "Hello Vue!".message.value is set to "Hello Vue!".const data = ref(null);
onMounted(() => {
const res = fetch('/api/items');
data.value = res.json();
});res.json() without awaiting means data.value gets a Promise, not actual data.Pass the test and this pattern moves unknown