nextTick方法

nextTick

当你在 Vue 中更改响应式状态时,最终的 DOM 更新并不是同步生效的,而是由 Vue 将它们缓存在一个队列中,直到下一个“tick”才一起执行。这样是为了确保每个组件无论发生多少状态改变,都仅执行一次更新。

nextTick() 可以在状态改变后立即使用,以等待 DOM 更新完成。你可以传递一个回调函数作为参数,或者 await 返回的 Promise。

用法一:传递一个回调函数作为参数

1<template>
2  <button id="counter" @click="increment">{{ count }}</button>
3</template>
4
5<script lang="ts" setup>
6import { ref, nextTick } from 'vue'
7const count = ref(0)
8
9async function increment() {
10  count.value++
11
12  // DOM 还未更新
13  console.log(document.getElementById('counter').textContent) // 0
14
15  nextTick(() => {
16    // DOM 此时已经更新
17    console.log(document.getElementById('counter').textContent) // 1
18  })
19}
20</script>

用法二:使用await

1<template>
2  <button id="counter" @click="increment">{{ count }}</button>
3</template>
4
5<script lang="ts" setup>
6import { ref } from 'vue'
7const count = ref(0)
8
9async function increment() {
10  count.value++
11
12  // DOM 还未更新
13  console.log(document.getElementById('counter').textContent) // 0
14
15  await nextTick()
16  // DOM 此时已经更新
17  console.log(document.getElementById('counter').textContent) // 1
18}
19</script>