vue3 nextTick()应用

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

在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>


打印结果:a09f0cd23422997d6931450688d7837f.png

如果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>


打印结果:

28f2a3ca3c8056746acf2283178f7c99.png



当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>

执行结果:

08aa70b02c2faf36be0b253447962f6f.png



总结

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


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


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


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


相关文章
|
3天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
12 0
|
3天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
3天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
18 0
|
3天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
20 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
8 1
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
7 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
6 0
|
3天前
|
JavaScript 前端开发 API
Vue3 系列:从0开始学习vue3.0
Vue3 系列:从0开始学习vue3.0
9 1
|
3天前
|
网络架构
Vue3 系列:vue-router
Vue3 系列:vue-router
8 2
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
7 1