/ 我有以下JSON数据。我需要列出从事特定学科的学生。如何在VUEJS中使用v-for完成此操作? /
students_subjects:
[
{
student_id:1,
student_name:"Moses",
reg_no:"ABC/2019",
subjects:[
{
subject_id:1
subject_name:"English"
},
{
subject_id:2
subject_name:"Maths"
}
]
},
{
student_id:2,
student_name:"James",
reg_no:"ABD/2019",
subjects:[
{
subject_id:1
subject_name:"English"
},
{
subject_id:2
subject_name:"Maths"
}
]
}
]
//我的html代码结构如下所示
<div id="app">
<ul>
<li v-for="item in students">
<div class="row " style="background-color: #f4fbee;">
<div class="col-md-2">{{item.reg_no}}</div>
</div>
<div class="row" v-for="subjects in item.subjects">{{subjects.subject_name}}
</div>
</li>
</ul>
<pre>{{students}}</pre>
<p>{{getStudentsBySubjectId}}</p>
</div>
var appVM=new Vue({
el:"#app",
data:function(){
return {
student_id: '',
reg_no:'',
student_name:'',
students:Array(),
subjects:{},
}
},
created:function (){
this.getAllStudents();
},
methods:{
getAllStudents:function(){
var self=this;
axios.get("/Students/list").then(function (response) {
this.students = response.data;
}.bind(this)).catch(function (error) {
console.log('Error while fetching student data: ' + error)
})
},
getStudentsBySubjectId:function (students, subjectId) {
return students.filter(function(student) {
return student.subjects.some(function(subject) {
return subject.subject_id === subjectId;
})
})
}
},
})
</script>
///我们如何显示已过滤的学生。 //上面的代码显示了在视图上调用数组时返回的数据
答案 0 :(得分:1)
假设您正在使用ES6。
这是您会发现所有学习特定学科的学生的方法:
function getStudentsBySubjectId(students, subjectId) {
return students.filter(student => student.subjects.some(subject => subject.subject_id === subjectId))
}
对于ES5,请使用常规功能代替箭头功能:
function getStudentsBySubjectId(students, subjectId) {
return students.filter(function(student) {
return student.subjects.some(function(subject) {
return subject.subject_id === subjectId;
})
})
}
您只需在上述函数返回的数组上v-for
。