如何确定Vue何时完成DOM更新?

时间:2015-04-06 12:25:06

标签: javascript dom vue.js

我希望在Vue创建内部<input>元素后访问它:

<li v-repeat="subtask: subtasks">
    <input v-model="subtask.name" type="text">
</li>

但是,此代码不起作用:

/* 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

然而,getElementById调用空手而归 - 当时节点不存在。

我什么时候可以确定Vue已经创建/更新了DOM?

3 个答案:

答案 0 :(得分:15)

Vue批处理DOM更新并出于性能原因异步执行它们。数据更改后,您可以使用Vue.nextTick等待DOM更新完成:

subtasks.push({});
Vue.nextTick(function () {
  // DOM updated
});

如果您在this可用的组件方法中使用它(以及对组件的引用),您可以使用:

this.$nextTick(function () {
  // DOM updated
});

参考文献:

Vue.nextTick

vm.$nextTick

答案 1 :(得分:1)

如果vue没有对此进行回调,您可以在父级上使用MutationObserver侦听器:https://developer.mozilla.org/en/docs/Web/API/MutationObserver

答案 2 :(得分:0)

这似乎对我有用

mounted() {
    window.addEventListener('load', (event) => {
    ...
    });
  },
相关问题