【问题标题】:How to determine when Vue has finished updating the DOM?如何确定 Vue 何时完成更新 DOM?
【发布时间】:2015-06-10 20:26:32
【问题描述】:

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

【问题讨论】:

    标签: javascript dom vue.js


    【解决方案1】:

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

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

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

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

    参考资料:

    Vue.nextTick

    vm.$nextTick

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        这似乎对我有用

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-20
          • 2020-04-21
          • 1970-01-01
          • 2015-08-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多