Consider this Vue 3 component using the Composition API. It fetches data asynchronously on mount.
import { ref, onMounted } from 'vue';
export default {
setup() {
const message = ref('Loading...');
onMounted(async () => {
await new Promise(resolve => setTimeout(resolve, 100));
message.value = 'Data loaded';
});
return { message };
}
}What text will be shown inside the component immediately after it mounts?
Think about when the async code finishes compared to the initial render.
The component initially sets message to 'Loading...'. The async code runs after mount and updates message after 100ms. So immediately after mount, the displayed text is still 'Loading...'.
Given this Vue 3 component snippet:
import { ref, onMounted } from 'vue';
export default {
setup() {
const count = ref(0);
onMounted(() => {
setTimeout(() => {
count.value += 1;
}, 50);
count.value += 1;
});
return { count };
}
}What is the value of count.value after 100ms?
Count how many times count.value is incremented and when.
Initially, count.value is 0. On mount, it increments by 1 immediately, then increments by 1 again after 50ms. After 100ms, the value is 2.
Which of these Vue 3 setup functions correctly fetches data asynchronously and updates a reactive variable?
Remember that setup cannot be async and reactive variables need to be refs.
Option B uses onMounted with an async function to fetch data and update a ref. Option B is invalid because setup cannot be async. Option B tries to assign to a const and uses await outside async. Option B works but does not use onMounted, so fetch may start too early.
Look at this Vue 3 setup code:
import { reactive, onMounted } from 'vue';
export default {
setup() {
const state = reactive({ count: 0 });
onMounted(() => {
setTimeout(() => {
state.count = state.count + 1;
}, 100);
});
return { state };
}
}After 100ms, the UI does not update to show the new count. What is the most likely reason?
Check if the template uses the reactive property to display the count.
The reactive state updates correctly, but if the template does not use state.count, Vue has no reason to re-render. The problem is likely in the template, not the code shown.
What happens if you declare the setup function as async in Vue 3, like this?
export default {
async setup() {
const data = await fetchData();
return { data };
}
}Choose the correct outcome and explanation.
Think about what Vue expects from the setup function return value.
Vue expects setup to return a plain object synchronously. Declaring it async makes it return a Promise, which Vue cannot handle, causing a runtime error.