admin管理员组

文章数量:1183730

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?

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?

Share Improve this question asked Apr 6, 2015 at 12:25 BryceBryce 6,61010 gold badges42 silver badges64 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 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

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

This seem to work for me

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

本文标签: javascriptHow to determine when Vue has finished updating the DOMStack Overflow