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 更新周期结束。
| 参数 | 描述 |
|---|---|
| callback function | 可选。所提供的回调函数将在 DOM 更新后运行(请参阅上面的实例) $nextTick() 方法也可以在没有参数的情况下使用(请参阅下面的实例) |
除了 this.$nextTick() 之外,还有一个全局 nextTick() 方法,即使在特定组件的范围之外,也可以用来等待 DOM 更新。
注意:在 Vue 中,当反应变量发生更改时,DOM 不会立即更新。Vue 保存这些更改,并在 'next tick' 发生时应用它们。这是为了增强性能并确保 Vue 实例和 DOM 之间的一致性。
更多实例
实例
通过在异步方法中调用带有 await 前缀的 $nextTick() 方法,可以获得与第一个实例相同的结果。这会导致下一行代码被搁置,直到 'next tick' 发生。
<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>