gpt4 book ai didi

javascript - VueJS v-for 循环在引用其他 ID 时中断

转载 作者:行者123 更新时间:2023-12-01 02:33:59 26 4
gpt4 key购买 nike

对 Vue 来说相对较新,我正在尝试构建比小部件更大的东西,但我遇到了障碍。

我试图在另一个对象的 v-for 循环内引用一个对象。即, session 循环内的 StudyID,因此我可以打印与其关联的研究的名称。

当我尝试访问循环中的整个研究对象时......它有效!

 <div v-for="session in sessions">
{{ studies[(session.studyId)] }} <br />
{{ session.interviewee }}
</div>

让我以 html 形式呈现

{ "id": 0, "name": "Usability", "description": "General usability tests", "createdDate": "12-31-2017" } 
Carol Danvers

<div v-for="session in sessions">
{{ studies[(session.studyId)].name }}
{{ session.interviewee }}
</div>

出现控制台错误,“TypeError: _vm.studies[session.studyId] 未定义”

当我对它进行硬编码时(即studies[0].name),它渲染得很好,这让我觉得我错过了 VueJs 如何评估表达式的一些细微差别。

下面的数据结构示例。

studies: [
{
'id' : 0,
'name' : "Usability",
'description' : 'General usability tests',
'createdDate' : '12-31-2017',
'script' : [
{ 'id': 0, 'string' : "Question 1: What do you see when you do X, Y or Z?" },
{ 'id': 1, 'string' : "Question 2: Where would you expect it to be?"},
{ 'id': 2, 'string' : "Question 3: Is there anything important you'd want us to know after all of this?"}
]
},
{
'id' : 1,
'name' : "Contextual Inquiry",
'createdDate' : '12-31-2017',
'description' : 'On-site interviews with our users!',
'script' : [
{ 'id': 0, 'string' : "Question 1: What do you see when you do X, Y or Z?" },
{ 'id': 1, 'string' : "Question 2: Where would you expect it to be?"},
{ 'id': 2, 'string' : "Question 3: Is there anything important you'd want us to know after all of this?"}
]
}
],
sessions: [
{
'interviewee': 'Carol Danvers',
'timestamp' : '',
'studyId' : 0,
'Notes': [
{
'relativeTimestamp' : 43,
'qID:': 0,
'authorID': '0',
'noteText': 'This is a note',
'tags' : [1]
},
{
'relativeTimestamp' : 17,
'qID:': 2,
'authorID': '1',
'noteText': 'This is another note',
'tags' : [1, 0, 2]
},
{
'relativeTimestamp' : 1,
'qID:': 2,
'authorID': '0',
'noteText': 'This is this working yet?',
'tags' : [2,5]
},
{
'relativeTimestamp' : 458,
'qID:': 3,
'authorID': '1',
'noteText': 'Oh hey, this is working!',
'tags' : [0,1]
}
]
},
{
'interviewee': 'Peter Parker',
'timestamp' : '',
'studyId' : 1,
'Notes': [ ]
},
{
'interviewee': 'Bruce Banner',
'timestamp' : '',
'studyId' : 0,
'Notes': [ ]
},
{}
],

最佳答案

查看您的数据 - 我发现您没有 sessions 中最后一项的 studyId 字段。
我相信它会导致问题,您应该以某种方式处理它,例如:

{{ studies[(session.studyId || 0)] }} <br />

<div v-for="session in sessions">
<template v-if="!!session.studyId">
{{ studies[(session.studyId)] }} <br />
{{ session.interviewee }}
</template>
</div>

或者在组件中创建一个计算属性validSessions,您可以在其中过滤掉空 session ,然后在模板中使用它,如下所示:

<div v-for="session in validSessions">
...
</div>

关于javascript - VueJS v-for 循环在引用其他 ID 时中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48087489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com