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

How to determine when Vue has finished updating the DOM?

我想在 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?

如果 vue 没有回调,你可以在父级上使用 MutationObserver 监听器:https://developer.mozilla.org/en/docs/Web/API/MutationObserver

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

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

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

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

参考文献:

Vue.nextTick

vm.$nextTick

这似乎对我有用

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