使用 Vuejs 嵌套 v-for
Posted
技术标签:
【中文标题】使用 Vuejs 嵌套 v-for【英文标题】:Nested v-for with Vuejs 【发布时间】:2020-09-08 22:26:01 【问题描述】:我已经研究了几个小时试图找出这个问题。目标是打印类似 google form 问卷的内容,其中包含 question_group、问题和答案。
我的数据层次结构是这样的:
question_group: [ str : "Addition",
questions: [ str: "1+1",
tipe: "multiple_choice",
answer_choice: [1, 2, 3, 4, 5]
,
str: "2+2",
tipe: "multiple_choice",
answer_choice: [1, 2, 3, 4, 5]
]
,
str : "Subtraction",
questions: [ str: "2-1",
tipe: "multiple_choice",
answer_choice: [1, 2, 3, 4, 5]
]
]
我的预期输出:
Addition
1. 1+1
a. 1
b. 2
c. 3
d. 4
e. 5
2. 2+2
a. 1
b. 2
c. 3
d. 4
e. 5
Subtraction
1. 2-1
a. 1
b. 2
c. 3
d. 4
e. 5
我想到的一个简单的循环例子是:
<div v-for="(group, i) in question_group" :key="'group' + i">
<div class="col-12">
<label> group.str </label>
</div>
<div v-for="(question, y) in questions" :key="'question' + y">
<label> index question.str </label>
<div v-for="(answer, z) in answer_choice" :key="'answer' + z">
<label> alphabet[index] . answer[z] </label>
</div>
</div>
</div>
【问题讨论】:
【参考方案1】:当您使用v-for
遍历数组时,第二个参数是条目的索引。
所以你的 html 应该是:
new Vue(
el: "#app",
data:
alphabet: ['a', 'b', 'c', 'd', 'e'],
question_group: [
str: "Addition",
questions: [
str: "1+1",
tipe: "multiple_choice",
answer_choice: [1, 2, 3, 4, 5]
,
str: "2+2",
tipe: "multiple_choice",
answer_choice: [1, 2, 3, 4, 5]
]
,
str: "Subtraction",
questions: [
str: "2-1",
tipe: "multiple_choice",
answer_choice: [1, 2, 3, 4, 5]
]
]
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(group, i) in question_group" :key="'group' + i">
<div class="col-12">
<label> group.str </label>
</div>
<div v-for="(question,y) in group.questions" :key="'question' + y">
<label> y+1 . question.str </label>
<div v-for="(answer,z) in question.answer_choice" :key="'answer' + z">
<label> alphabet[z] . answer</label>
</div>
</div>
</div>
</div>
更多信息请访问the official documentation。
【讨论】:
【参考方案2】:你的意思是这样的?
<div v-for="(group, i) in question_group" :key="'group' + i">
<div class="col-12">
<label> group.str </label>
</div>
<div v-for="(question, y) in group.questions" :key="'question' + y">
<label> index question.str </label>
<div v-for="(answer, z) in question.answer_choice" :key="'answer' + z">
<label> alphabet[index] . answer[z] </label>
</div>
</div>
</div>
【讨论】:
【参考方案3】:这是解决问题的一种方法
<div id="app">
<div v-for="(group, i) in question_group" :key="'group' + i">
<div class="col-12">
<label> group.str </label>
</div>
<div v-for="(question, question_index) in group.questions" :key="'question' + question_index">
<label> question_index + 1 question.str </label>
<ol type='a'>
<li v-for="(answer, answer_index) in question.answer_choice" :key="'answer' + answer_index"> answer </li>
</ol>
</div>
</div>
</div>
【讨论】:
以上是关于使用 Vuejs 嵌套 v-for的主要内容,如果未能解决你的问题,请参考以下文章