Vue.nextTick() 使用场景及实现原理

Vue.nextTick() 基本使用

作用: 等待下一次 DOM 更新刷新的工具方法。

  1. 为什么需要用到Vue.nextTick()?

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

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

  2. Vue.nextTick() 和 this.$nextTick() 的区别

    vue中this.$nextTick() 是绑定在实例上的 nextTick() 函数。和全局版本的 nextTick()
    的唯一区别就是组件传递给 this.$nextTick() 的回调函数会带上 this 上下文,其绑定了当前组件实例。

  3. Vue.nextTick() 使用场景

    获取数据更新后的dom元素,或者在数据更新后操作dom

  4. Vue.nextTick() 实现原理 点击查看
  5. 使用示例:
    <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>
    

相关推荐

  1. Vue nextTick使用场景实现原理

    2024-04-09 17:42:02       49 阅读
  2. Vue.nextTick() 使用场景实现原理

    2024-04-09 17:42:02       37 阅读
  3. Android malloc_debug实现原理使用

    2024-04-09 17:42:02       30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-09 17:42:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-09 17:42:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-09 17:42:02       82 阅读
  4. Python语言-面向对象

    2024-04-09 17:42:02       91 阅读

热门阅读

  1. DockerFile定制镜像

    2024-04-09 17:42:02       32 阅读
  2. Vue3 · 小白学习全局 API:常规

    2024-04-09 17:42:02       36 阅读
  3. 面试前必看,仅供参考

    2024-04-09 17:42:02       33 阅读
  4. 蓝桥杯算法题:蓝桥公园

    2024-04-09 17:42:02       38 阅读
  5. 图神经网络学习记录——图信号处理常见方法

    2024-04-09 17:42:02       35 阅读
  6. python pytest 面试题

    2024-04-09 17:42:02       38 阅读
  7. spring获取bean

    2024-04-09 17:42:02       31 阅读
  8. # 计算机视觉入门

    2024-04-09 17:42:02       34 阅读
  9. 算法刷题记录 Day41

    2024-04-09 17:42:02       39 阅读
  10. 外观模式(面子模式)

    2024-04-09 17:42:02       33 阅读