11

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?

3 Answers 3

28

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

Sign up to request clarification or add additional context in comments.

1 Comment

For Vue 3 with composition API just: nextTick(() => { ... your code ... }). See: nextTick()
2

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

Comments

0

This seem to work for me

mounted() { window.addEventListener('load', (event) => { ... }); }, 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.