Consider this Vue 3 component using nextTick. What will be logged to the console?
import { ref, nextTick } from 'vue'; export default { setup() { const count = ref(0); function increment() { count.value++; console.log('Before nextTick:', count.value); nextTick(() => { console.log('Inside nextTick:', count.value); }); } return { count, increment }; } };
Remember that count.value updates immediately, but DOM updates happen after nextTick.
The count.value is incremented immediately, so the first log shows 1. The nextTick callback runs after DOM updates, but the reactive value remains 1, so the second log also shows 1.
Given this Vue 3 component, what will be the content of the <div> after the nextTick callback runs?
<template>
<div>{{ message }}</div>
<button @click="updateMessage">Update</button>
</template>
<script setup>
import { ref, nextTick } from 'vue';
const message = ref('Hello');
function updateMessage() {
message.value = 'Updated';
nextTick(() => {
const div = document.querySelector('div');
console.log(div.textContent);
});
}
</script>Think about when the DOM updates happen relative to nextTick.
The message is updated before nextTick. The callback runs after the DOM updates, so the div's text content is 'Updated'.
In this Vue 3 setup, the nextTick callback logs the old DOM content instead of the updated one. What is the cause?
<template> <p ref="para">Old</p> <button @click="changeText">Change</button> </template> <script setup> import { ref, nextTick } from 'vue'; const para = ref(null); function changeText() { para.value.textContent = 'New'; nextTick(() => { console.log(para.value.textContent); }); } </script>
Consider how Vue tracks changes and when nextTick triggers.
Manually changing DOM elements directly does not trigger Vue's reactivity system. Therefore, nextTick does not wait for these changes, and the callback sees the old content.
Choose the correct way to use nextTick to run code after DOM updates.
Remember nextTick returns a Promise and can be awaited or passed a callback function.
Option C correctly passes a callback function to nextTick, which executes after the DOM update cycle. Option A logs immediately and passes undefined to nextTick. Option B is invalid syntax since nextTick is a function, not a Promise instance. Option D requires an async function context to use await.
Which statement best explains the purpose of nextTick in Vue 3?
Think about when DOM updates happen relative to reactive data changes.
nextTick schedules a callback to run after Vue finishes updating the DOM to reflect reactive data changes. This allows code to safely access the updated DOM.