对Vue来说相对较新,我试图构建比小部件更大的东西,而且我遇到了路障。
我试图引用另一个对象的v-for循环内的一个对象。即,Sessions循环中的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>
给我一个控制台错误,&#34; TypeError:_vm.studies [session.studyId]未定义&#34;
当我对它进行硬编码时(即研究[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': [ ]
},
{}
],
答案 0 :(得分:2)
查看您的数据 - 我发现studyId
中的最后一项没有sessions
字段。
我相信它会导致问题,你应该以某种方式处理它,例如:
{{ 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
,您可以在其中过滤掉空会话,然后在您的模板中使用它,如下所示:
<div v-for="session in validSessions">
...
</div>