3 min read
•Question 23 of 37mediumWhat is nextTick in Vue?
Waiting for DOM updates.
What You'll Learn
- What nextTick does
- When to use it
- Async/await with nextTick
The Problem
code.jsJavaScript
const count = ref(0)
count.value = 1
console.log(document.getElementById('count').textContent)
// Still shows 0! DOM hasn't updated yetUsing nextTick
code.jsJavaScript
import { nextTick } from 'vue'
const count = ref(0)
count.value = 1
nextTick(() => {
console.log(document.getElementById('count').textContent)
// Now shows 1
})Async/Await
code.jsJavaScript
async function updateAndRead() {
count.value = 1
await nextTick()
// DOM is now updated
console.log(document.getElementById('count').textContent)
}Common Use Cases
code.jsJavaScript
// Focus input after showing
showInput.value = true
await nextTick()
inputRef.value.focus()
// Get updated element dimensions
items.value.push(newItem)
await nextTick()
const height = listRef.value.scrollHeight