我有以下嵌套的Javascript数组,我希望使用vue v-for循环将其生成到一个表中(输出中显示了最终的html )。最好的方法是什么?我尝试过嵌套的v-for循环,但结果是错误的。
输入:
[{ "school_name": "Test School A", "classes": [{ "class_name": "Class A", "students": [ { "student_name": "John", "grade" : "A"} { "student_name": "Andrew", "grade" : "B"} { "student_name": "Peter", "grade" : "C"} "class_name": "Class B", "students": [ { "student_name": "Alice", "grade" : "C"} { "student_name": "Ronald", "grade" : "A"} { "student_name": "Katherine", "grade" : "B"} }]},{ "school_name": "Test School B", "classes": [{ "class_name": "Class C", "students": [ { "student_name": "John", "grade" : "B"} { "student_name": "Ronald", "grade" : "B"} { "student_name": "Jacob", "grade" : "B"} "class_name": "Class D", "students": [ { "student_name": "Maia", "grade" : "C"} { "student_name": "Narine", "grade" : "C"} { "student_name": "Olivia", "grade" : "A"} }]}]
输出
<table> <tbody> <td rowspan="6">School A</td> <td rowspan="3">Class A</td> <td>John</td> <td>Peter</td> <td>Andrew</td> <td rowspan="3">Class B</td> <td>Alice</td> <td>Ronald</td> <td>Katherine</td> </tbody> </table>
发布于 2018-05-28 09:19:41
我不能让它变得更好,也不能让它变得更有活力,但它将正好满足您的需求。
<template> <div id="app"> <table border="1" style="border-collapse: collapse"> <tbody> <template v-for="(school, currentSchool) in data"> <template v-for="(schoolClass, currentClass) in school.classes"> <tr v-for="(student, currentStudent) in schoolClass.students"> <td v-if="currentStudent+currentClass == 0" :rowspan="rowspanSchool[school.school_name]"> {{school.school_name}} <td v-if="currentStudent == 0" :rowspan="rowspanClass[schoolClass.class_name]">{{schoolClass.class_name}}</td> <td>{{student.student_name}}</td> </template> </template> </tbody> </table> </template> <script> export default { name: 'app', computed: { rowspanSchool() { let schoolSpans = {}; for (let school in this.data) { let total = 0; for (let schoolClass in this.data[school].classes) { for (let student in this.data[school].classes[schoolClass].students) { total++; schoolSpans[this.data[school].school_name] = total; return schoolSpans rowspanClass() { let classSpans = {}; for (let school in this.data) { for (let schoolClass in this.data[school].classes) { let total = 0; for (let student in this.data[school].classes[schoolClass].students) { total++; classSpans[this.data[school].classes[schoolClass].class_name] = total; return classSpans data() {