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 更新週期完成。
引數 | 描述 |
---|---|
回撥函式 | 可選。提供的回撥函式將在 DOM 更新後執行(見上面的示例)。$nextTick() 方法也可以不帶引數使用(見下面的示例)。 |
除了 this.$nextTick()
之外,還有一個全域性的 nextTick()
方法,可以用於等待 DOM 更新,即使在特定元件的作用域之外也可以使用。
注意:在 Vue 中,當響應式變數改變時,DOM 不會立即更新。Vue 會快取這些更改,並在“下一個 tick”發生時應用它們。這是為了提高效能並確保 Vue 例項和 DOM 之間的一致性。
更多示例
示例
透過在非同步方法中使用 await
字首呼叫 $nextTick()
方法,可以實現與第一個示例相同的結果。這將使接下來的程式碼行暫停,直到“下一個 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>
執行示例 »
相關頁面
JavaScript 教程:JavaScript Async
Vue 教程: Vue 方法
Vue 教程:Vue Template Refs
Vue 教程:Vue v-on
Vue 教程:Vue 事件修飾符
Vue 參考:Vue 'ref' 屬性
Vue 參考:Vue $refs 物件