Vue $nextTick() 方法


示例

使用$nextTick()方法在我们获取消息之前等待 DOM 更新<p>标签。

methods: {
  updateMsg() {
    this.message = '"Hello! This is a new message."';
    this.results.push(this.$refs.pEl.textContent);
    this.$nextTick(() => {
      this.results.push(this.$refs.pEl.textContent + ' (using $nextTick())');
    });
  }
}
运行示例 »

请参阅下面的更多示例。


定义和用法

这个$nextTick()方法在执行之前等待 DOM 更新。

我们用this.$nextTick()等待当前Vue组件的DOM更新周期完成。

Argument Description
callback function Optional. The callback function provided will run after the DOM is updated (see the example above). The $nextTick() method can also be used without an argument (see the example below).

此外this.$nextTick()还有一个全球性的nextTick()方法可用于等待 DOM 更新,甚至可以从特定组件的范围之外进行更新。

笔记:在 Vue 中,当响应式变量发生更改时,DOM 不会立即更新。 Vue 会保存这些更改,并在“下一个刻度”发生时应用它们。这是为了增强性能并确保 Vue 实例和 DOM 之间的一致性。


更多示例

示例

通过调用可以实现与第一个示例相同的结果$nextTick()方法与await异步方法中的前缀。这会导致下一行代码被搁置,直到“下一个刻度”发生。

<template>
  <h2>Example $nextTick() Method</h2>
  <p>Using "await $nextTick()", the next lines of code will also wait until the 'next tick' happens.
  </p>
  <div>
    <p ref="messageEl">{{ message }}</p>
    <button v-on:click.once="updateMsg">Update Message</button>
    <ol>
      <li v-for="x in results">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: "Initial Message",
      results: []
    };
  },
  methods: {
    async updateMsg() {
      this.message = "Hello! This message is now updated.";
      this.results.push(this.$refs.messageEl.textContent);
      await this.$nextTick();
      this.results.push(this.$refs.messageEl.textContent + ' (after await $nextTick())');
    }
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>
运行示例 »

相关页面

JavaScript 教程:JavaScript 异步

Vue教程:Vue 方法

Vue教程:Vue 模板参考

Vue教程:Vue v-on

Vue教程:Vue 事件修饰符

Vue参考:Vue 'ref' 属性

Vue参考:Vue $refs 对象