我想在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次呼叫空手而归—— node 当时不存在.

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

推荐答案

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

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

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

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

参考资料:

Vue.nextTick

vm.$nextTick

Vue.js相关问答推荐

Vue路由路径匹配行为

如何将$validator实例注入到使用组合API语法的Vue2.7应用程序中

Vue ChildComponent (GrandchildComponent) 应该更新 ParentComponent 的列表

Vue 3 需要 main.js 中的文件

NUXT 3 在客户端获取数据

vue3 + pinia:如何从?store 中获取一个值

如何在 vue js 的一页路由下显示不同的 category._id

在 Vue 文件中创建根 Vue 实例

指定一个 vue-cli vue.config.js 位置

动态插入字符串上的 Vue 事件处理程序不起作用

包含 Vue.js v-if 和 v-for 指令的 HTML 标签在加载时flash

Vue Prop 没有初始化器,也没有在构造函数中明确赋值

在Vue.js中从父组件执行子方法

如何在 Vue 中动态创建组件上获取更新的 $refs?

错误:Node Sass 尚不支持您当前的环境:Linux 64-bit with Unsupported runtime (88)

Vue在按钮单击时添加一个组件

Vue cli 在 css 中构建生产更改不透明度

标签中的 href 赋值

为什么 router.currentRoute.path 没有react?

这个业务逻辑有多少属于 Vuex?