我在显示数据库表查找方法的结果方面遇到了laravel和vue的问题。我不太明白的是,为什么v-for指令解析json结果不正确。
这是Vue代码:
<template>
<table class="table table-hover">
<thead>
<tr>
<th>Class</th>
<th>Amount of Students</th>
<th>Teacher</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="classroom in classrooms" :key="classroom.id">
<td>{{ classroom.class_no }}•{{ classroom.field }}•{{ classroom.room_no }}</td>
<td>{{ classroom.amount_students }}</td>
<td>{{ classroom.teacher }}</td>
<td>
<a href="#">
<i class="fa fa-edit blue"></i>
</a>
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data () {
return {
classrooms : {
"success": true,
"data": { "id": 1, "class_no": 1, "field": "Architecture", "room_no": 4, "amount_students": 40, "teacher": "Bobby Fisher" },
"message": "Find Classroom Detail"
}
}
}
}
</script>
json教室本身实际上是来自控制器的结果:
public function show($level)
{
$classrooms = ClassRoom::where('class_no', $level)->firstOrFail();
return $this->sendResponse($classrooms , 'Find Classroom Detail');
}
下面是错误结果的截图:
结果应该只是单行
请帮我解决这个问题。
实际上,当你在教室上迭代时,教室是一个有三个键的对象,所以for循环在每个键上迭代一次。
如果您只想对data
密钥进行迭代,那么只需从后端返回数据即可。
您可以使用v-if
条件来检查当前键是否包含class_no,如果是,则显示该行,否则不显示。
<tr v-for="classroom in classrooms" :key="classroom.id" v-if="classroom.class_no">
<td>{{ classroom.class_no }}•{{ classroom.field }}•{{ classroom.room_no }}</td>
<td>{{ classroom.amount_students }}</td>
<td>{{ classroom.teacher }}</td>
<td>
<a href="#">
<i class="fa fa-edit blue"></i>
</a>
</td>
</tr>
查看Vue数据属性,您希望使用v-for="classroom in classrooms.data"
。如果你从API获取数据,那么你不想将完整响应分配给你的classroom
数据属性,而是将response.data
分配给classroom
,这样你就可以进行
v-for="classroom in classrooms"
。
除非API以不同的格式返回数据,否则这将起作用。
您可以查看JsFiddle
https://jsfiddle.net/JManish/9qjvdy8n/2/
对教室的数据属性进行一些更改。
<table class="table">
<thead>
<tr>
<th>Class</th>
<th>Amount of Students</th>
<th>Teacher</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(classroom, index) in classrooms.data" :key="index">
<td>{{ classroom.class_no }}•{{ classroom.field }}•{{ classroom.room_no }}</td>
<td>{{ classroom.amount_students }}</td>
<td>{{ classroom.teacher }}</td>
<td>
<a href="#">
<i class="fa fa-edit blue"></i>
</a>
</td>
</tr>
</tbody>
</table>
new Vue({
el: '#app',
data() {
return {
classrooms: {
"success": true,
"data":[
{
"id": 1,
"class_no": 1,
"field": "Architecture",
"room_no": 4,
"amount_students": 40,
"teacher": "Bobby Fisher"
}
],
"message": "Find Classroom Detail"
}
}
}
})
希望这将解决您的解析问题。