I want to access the inner <input>
element after it has been created by Vue:
<li v-repeat="subtask: subtasks">
<input v-model="subtask.name" type="text">
</li>
However, this code does not work:
/* add a new item (that in turn will create a new DOM node) */
subtasks.push({
name: 'wash the dishes',
id: 'box-123'
});
/* ... Around now, Vue should get busy creating the new <li> ... */
/* Now the element should exist, but it doesn't */
console.log(document.getElementById('box-123'));
// --> null
However, the getElementById
call comes back empty handed--the node does not exist at that time.
When can I be sure Vue has created / updated the DOM?
Virtual DOM in Vue is a JavaScript object that represents the Document Object Model (DOM). The application updates the Virtual DOM instead of the DOM directly. So, it minimizes the updating cost of the real DOM as it is computationally expensive.
In a nutshell So: nextTick is a comfortable way to execute a function after the data has been set and the DOM has updated.
Vue uses a virtual DOM because of the sheer difference in speed and efficiency compared to the actual DOM. The virtual DOM is also smaller in size than the actual DOM and so is very efficient.
Vue batches DOM updates and performs them asynchronously for performance reasons. After a data change, you can use Vue.nextTick
to wait for the DOM updates to finish:
subtasks.push({});
Vue.nextTick(function () {
// DOM updated
});
If you are using it inside a component method where this
is available (and a reference to the component), you can use:
this.$nextTick(function () {
// DOM updated
});
References:
Vue.nextTick
vm.$nextTick
If vue does not have a callback for this you can use a MutationObserver listener on the parent: https://developer.mozilla.org/en/docs/Web/API/MutationObserver
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With