Vue batch DOM updates — không update ngay khi state thay đổi, mà queue updates và flush async. nextTick cho phép chờ DOM được update xong:
javascript
import { nextTick, ref } from 'vue'
const count = ref(0)
async function handleClick() {
count.value++
// DOM chưa update ở đây
await nextTick()
// DOM đã update — giờ có thể đọc DOM hoặc scroll
console.log(document.querySelector('.count')?.textContent)
}Dùng khi:
- Cần đọc DOM sau khi state update
- Focus element sau khi v-if toggle
- Scroll sau khi append item vào list
Vue batches DOM updates — doesn't update immediately when state changes, queues updates and flushes async. nextTick waits for DOM to finish updating:
javascript
import { nextTick, ref } from 'vue'
const count = ref(0)
async function handleClick() {
count.value++
// DOM not yet updated here
await nextTick()
// DOM is now updated — safe to read DOM or scroll
console.log(document.querySelector('.count')?.textContent)
}Use when:
- Need to read DOM after state update
- Focus an element after v-if toggle
- Scroll after appending items to a list