Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine when Vue has finished updating the DOM?

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?

like image 634
Bryce Avatar asked Apr 06 '15 12:04

Bryce


People also ask

How does Vue update 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.

Which method is used to make sure a change is performed after the DOM has been updated?

In a nutshell So: nextTick is a comfortable way to execute a function after the data has been set and the DOM has updated.

Does Vue use DOM?

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.


2 Answers

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

like image 142
Evan You Avatar answered Oct 07 '22 01:10

Evan You


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

like image 23
Mircea Avatar answered Oct 07 '22 01:10

Mircea