跳到主要内容

nextTick

2023年07月19日
柏拉文
越努力,越幸运

一、认识


nextTick 在下次 DOM 更新循环结束之后执行延迟回调。一般用于修改数据之后, 立即使用 nextTick 获取更新后的 DOM

Vue 有个机制,更新 DOM 是异步执行的,当数据变化会产生一个异步更行队列,要等异步队列结束后才会统一进行更新视图,所以改了数据之后立即去拿 DOM 还没有更新就会拿不到最新数据。所以提供了一个 nextTick 函数,它的回调函数会在DOM 更新后立即执行。

二、语法


<script setup>
import { ref, nextTick } from 'vue'

const count = ref(0)

async function increment() {
count.value++

// DOM 还未更新
console.log(document.getElementById('counter').textContent) // 0

await nextTick()
// DOM 此时已经更新
console.log(document.getElementById('counter').textContent) // 1
}
</script>

<template>
<button id="counter" @click="increment">{{ count }}</button>
</template>