vue3 nextTick()应用

在Vue3中,可以使用nextTick函数来延迟执行某些操作,这些操作会在下一次DOM更新周期之后执行。这个函数通常用于在数据更新后,等待DOM更新之后执行一些操作,比如获取DOM元素的尺寸、位置等。

nextTick()

例如,以下一个切换元素显示的组件:

<template>
  <div>
    <button @click="handleClick">显示/移除</button>
    <div v-if="show" ref="content">我是一个元素</div>
  </div>
</template>
<script setup>
import { ref } from 'vue'
const show = ref(true)
const content = ref()
const handleClick = () => {
  show.value = !show.value
  console.log(show.value, content.value)//true null
}
</script>

打印结果:

如果show是true,那么content是null,这意味着 DOM 与组件的数据不同步。

我们加上nextTick()

<template>
  <div>
    <button @click="handleClick">显示/移除</button>
    <div v-if="show" ref="content">我是一个元素</div>
  </div>
</template>
<script setup>
import { ref, nextTick } from 'vue'
const show = ref(true)
const content = ref()
const handleClick = () => {
  show.value = !show.value
  nextTick(() => {
    console.log(show.value, content.value)
  })
}
</script>

打印结果: 

当show为true时,获取到dom。

nextTick() 与异步/等待

如果nextTick()不带参数调用,则该函数返回一个promise,该promise在组件数据更改到达 DOM 时解析。

这有助于利用更具可读性的async/await语法。 如下例子:

<template>
  <div>
     <button @click="handleClick">显示/移除</button>
    <div v-if="show" ref="content">我是一个元素</div>
  </div>
</template>
<script setup>
import { ref, nextTick } from 'vue'
const show = ref(true)
const content = ref()
const handleClick = async () => {
  show.value = !show.value
   console.log(show.value, content.value)
  await nextTick()
  console.log(show.value, content.value)
}
</script>

执行结果: 

总结

当你更改组件的数据时,Vue3 会异步更新 DOM。

如果你想捕捉组件数据变化后 DOM 更新的时刻,那么你需要使用nextTick(callback) 函数。

它们的单个callback参数在 DOM 更新后立即被调用:并且你可以保证获得与组件数据同步的最新 DOM。

或者,如果你不向nextTick() 提供回调参数,那么这些函数将返回一个在 DOM 更新时被解析的promise

猜你喜欢

转载自blog.csdn.net/qq_48652579/article/details/130601760
今日推荐