【发布时间】:2020-04-18 23:13:33
【问题描述】:
每次渲染组件时,我都在努力使其正常工作即使我为索引传递了另一个值。基本上,我将一个索引值传递给了输入文本元素的 ref,它位于组件的 v-for 循环内,所以在mounted(),我有一些东西像这样
mounted() {
this.$nextTick(() =>
{
this.$refs.newInp[index].focus();
});
}
但即使我传递了 1 或 2 的值,它仍然专注于第一个输入元素。当我查看控制台日志时,它会在控制台上显示此错误。
TypeError:无法读取未定义的属性“0”
指向这条线this.$refs.newInp[index].focus();
获取 v-for 中数据的示例代码
async GetContentDetails() {
let testRes =
await axios.get('myUrl/api', {
params: {
ContentId: this.$cookie.get('OpV-ContId')
}
}).then(res => this.contentItems = res.data)
.then()
.catch(error => console.log(error));
this.testData = testRes;
}
模板:
<div v-for="(contItem, index) in contentItems" :key="contItem.commentId">
<textarea class="reply-commented" ref="newInp"></textarea>
</div>
如何解决此类问题?解决方案是什么? 谢谢。
【问题讨论】:
-
放最少的代码来理解
-
@Rahul - 你还需要什么代码?那是我曾经关注的唯一代码。你不明白哪一部分?
-
您的 v-for 循环数据是异步获取的,因为在这种情况下,输入字段将在获取数据后创建,并且在挂载的钩子中无法访问该字段,因此出现错误。如果没有,你能用小提琴重现它吗?
-
newInp未定义。也许是v-if或类似的东西。我们可以看看模板吗? -
@Himanshu - 是的,在 v-for 循环中获取的数据使用异步,就像这个异步 GetContentDetails() { let testRes = await axios.get('myUrl/api', { params : { ContentId: this.$cookie.get('OpV-ContId') } }).then(res => this.contentItems = res.data) .then() .catch(error => console.log(error) ); this.testData = testRes; }
标签: javascript vue.js vuejs2 vuejs3