$nextTick()
时间: 2023-10-13 19:28:08 浏览: 47
$nextTick() is a method in Vue.js that allows you to wait for the next tick of the JavaScript event loop before executing a function. This is useful when you need to modify the DOM after a data change has been made, but the DOM has not yet been updated to reflect that change.
For example, let's say you have a component with a computed property that depends on some data. If you try to access that computed property immediately after changing the data, you may not get the updated value because the DOM has not yet been updated.
Using $nextTick(), you can ensure that the DOM has been updated before accessing the computed property. Here's an example:
```
<template>
<div>
<p>{{ message }}</p>
<button @click="changeMessage">Change message</button>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello world'
}
},
methods: {
changeMessage() {
this.message = 'New message'
this.$nextTick(() => {
console.log(this.$el.textContent) // Output: 'New message'
})
}
}
}
</script>
```
In the above example, we have a button that changes the value of `message` when clicked. We use $nextTick() to log the updated message to the console after the DOM has been updated.
阅读全文