vue接受后端传来的数据实现课表展示的代码
时间: 2023-06-12 12:04:22 浏览: 124
假设后端传来的数据格式如下:
```json
{
"weekdays": [
{
"day": "Monday",
"courses": [
{
"name": "Math",
"time": "9:00-10:30",
"location": "Room 101"
},
{
"name": "Physics",
"time": "11:00-12:30",
"location": "Room 102"
}
]
},
{
"day": "Tuesday",
"courses": [
{
"name": "English",
"time": "9:00-10:30",
"location": "Room 103"
},
{
"name": "History",
"time": "11:00-12:30",
"location": "Room 104"
}
]
},
// ...
]
}
```
我们可以通过 Vue 的模板语法将数据渲染到页面上,示例代码如下:
```html
<template>
<div>
<table>
<thead>
<tr>
<th>Weekday</th>
<th>Course</th>
<th>Time</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr v-for="weekday in weekdays" :key="weekday.day">
<td>{{ weekday.day }}</td>
<td v-for="course in weekday.courses" :key="course.name">{{ course.name }}</td>
<td v-for="course in weekday.courses" :key="course.time">{{ course.time }}</td>
<td v-for="course in weekday.courses" :key="course.location">{{ course.location }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
weekdays: []
}
},
mounted() {
// 假设后端接口为 /api/schedule
axios.get('/api/schedule').then(response => {
this.weekdays = response.data.weekdays
})
}
}
</script>
```
这段代码中,我们使用了 Vue 的模板语法和 v-for 指令进行数据渲染。由于课表是以表格的形式呈现,我们使用了 table 元素和相应的表头和表体。在表体中,我们使用了 v-for 指令来遍历数据,并将数据展示到表格中。
在 mounted 钩子函数中,我们向后端接口发送请求,并将返回的数据赋值给 weekdays 数组,从而完成了课表的展示。
阅读全文