nextTick 是 Vue 3 中用于完成数据绑定和 DOM 更新后执行的方法,非常有用,也是 Vue 的一道比较常见的面试题。
1. 基本用法
nextTick 是一个异步方法,它允许我们在下一个 DOM 更新后执行回调函数。当更改了响应式数据并需要在更新后的 DOM 元素上执行操作时,可以使用 nextTick。
<template>
<div>
<p ref="pRef">message:{
{ message }}</p>
<button @click="updateMessage">Update Message</button>
</div>
</template>
<script setup>
import { ref, nextTick } from 'vue'
const message = ref('Hello, World!')
const pRef = ref(null)
const updateMessage = () => {
message.value = 'Message Updated!' // 在 DOM 更新后执行
nextTick(() => {
console.log(pRef.value.textContent) // 输出 'Message Updated!'
})
}
</script>