vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue中nextTick原理

Vue中nextTick的原理分析

作者:遇见很ok

本文详细介绍了Vue中nextTick的原理和使用方法,Vue采用异步渲染机制,通过nextTick可以确保在DOM更新后执行回调,nextTick依赖微任务和宏任务,优先使用Promise,降级到MutationObserver/setTimeout,Vue3进一步优化了nextTick,减少了复杂度并提升了性能

Vue中nextTick原理

1. 为什么需要 nextTick

Vue 采用 异步渲染机制,当响应式数据发生变化时,Vue 并不会立即更新 DOM,而是将这些变化放入一个 队列 中,并在 同一事件循环(Event Loop)中合并相同的修改,最后执行批量更新。

这样做的目的是 提升性能,避免不必要的重复渲染

例如:

<template>
  <div>{{ msg }}</div>
</template>

<script>
export default {
  data() {
    return {
      msg: "Hello"
    };
  },
  mounted() {
    this.msg = "Vue";
    console.log(document.querySelector("div").innerText); // 仍然是 "Hello"
    this.$nextTick(() => {
      console.log(document.querySelector("div").innerText); // 现在是 "Vue"
    });
  }
};
</script>

为什么 console.log 还是 "Hello"?

因为 Vue 在 this.msg = "Vue"不会立即更新 DOM,而是等本轮事件循环结束后再更新。因此,我们需要 nextTick 来确保获取到更新后的 DOM。

2. nextTick 的原理

Vue 的 nextTick 本质上是一个 异步任务调度器,它会在当前 DOM 任务完成后执行回调。其内部原理主要依赖 微任务(Microtask)和 宏任务(Macrotask)

2.1 任务队列

Vue 内部维护了一个 回调队列(callback queue),当 nextTick 被调用时,它会将回调函数 推入队列,然后等待 Vue 进行 DOM 更新后,再依次执行这些回调。

2.2 任务调度策略

nextTick 采用 优雅降级 的策略,在不同环境下选择最佳的异步方法:

  1. Promise(Microtask)(首选,现代浏览器支持)
  2. MutationObserver(Microtask)(比 setTimeout 更快)
  3. setImmediate(Macrotask)(仅 IE 支持)
  4. setTimeout(Macrotask)(最后的兜底方案)

代码实现:

function nextTick(callback) {
  const p = Promise.resolve();
  p.then(callback);
}

在 Vue 3 中:

let callbacks = [];
let pending = false;

function flushCallbacks() {
  pending = false;
  const copies = callbacks.slice(0);
  callbacks.length = 0;
  for (let cb of copies) {
    cb();
  }
}

export function nextTick(cb) {
  callbacks.push(cb);
  if (!pending) {
    pending = true;
    Promise.resolve().then(flushCallbacks);
  }
}

流程解析:

  1. 每次调用 nextTick(cb),将 cb 放入 callbacks 队列中。
  2. 只要 pending === false,就启动 微任务(Promise.then)
  3. 微任务执行 flushCallbacks,依次调用 callbacks 队列中的所有回调。

3. nextTick 在 Vue 2 和 Vue 3 的区别

3.1 Vue 2 的 nextTick

在 Vue 2 中,nextTick 主要依赖:

3.2 Vue 3 的 nextTick

Vue 3 主要优化:

Vue 3 中的 nextTick

const resolvedPromise = Promise.resolve();
export function nextTick(fn) {
  return fn ? resolvedPromise.then(fn) : resolvedPromise;
}

优化点

4. nextTick 的使用场景

4.1 在 DOM 更新后执行操作

<template>
  <div ref="box">{{ message }}</div>
</template>

<script>
export default {
  data() {
    return { message: "Hello" };
  },
  methods: {
    updateMessage() {
      this.message = "Vue";
      this.$nextTick(() => {
        console.log(this.$refs.box.innerText); // "Vue"
      });
    }
  }
};
</script>

4.2 在 watch 中等待 DOM 更新

watch(() => state.count, async (newVal) => {
  await nextTick();
  console.log(document.querySelector("#counter").innerText); // 确保 DOM 已更新
});

4.3 在 Vue 3 setup 中使用

import { nextTick, ref } from "vue";

setup() {
  const message = ref("Hello");
  
  const updateMessage = async () => {
    message.value = "Vue";
    await nextTick();
    console.log(document.querySelector("#msg").innerText);
  };

  return { message, updateMessage };
}

总结

你可以简单理解为:

Vue 在修改数据后,不会立即更新 DOM,而是 批量合并修改,并在下一次 事件循环(Event Loop)结束时更新 DOMnextTick 让你可以等到 DOM 更新完成后再执行操作。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文