vue实现赛程表
Vue 实现赛程表
数据结构设计
赛程表的核心是赛事数据的组织,通常需要包含比赛时间、对阵双方、比分等信息。可以使用数组对象存储数据,每个对象代表一场比赛。
data() {
return {
matches: [
{ id: 1, date: '2023-10-01', teamA: 'Team A', teamB: 'Team B', scoreA: 2, scoreB: 1 },
{ id: 2, date: '2023-10-02', teamA: 'Team C', teamB: 'Team D', scoreA: 0, scoreB: 0 },
// 更多比赛数据...
]
}
}
基础表格渲染
使用 v-for 指令循环渲染比赛数据,构建基础的赛程表格。
<table class="schedule-table">
<thead>
<tr>
<th>日期</th>
<th>主队</th>
<th>比分</th>
<th>客队</th>
</tr>
</thead>
<tbody>
<tr v-for="match in matches" :key="match.id">
<td>{{ match.date }}</td>
<td>{{ match.teamA }}</td>
<td>{{ match.scoreA }} - {{ match.scoreB }}</td>
<td>{{ match.teamB }}</td>
</tr>
</tbody>
</table>
按日期分组
对于多日赛事,可以按日期分组显示比赛。使用计算属性对数据进行分组处理。
computed: {
groupedMatches() {
const groups = {};
this.matches.forEach(match => {
if (!groups[match.date]) {
groups[match.date] = [];
}
groups[match.date].push(match);
});
return groups;
}
}
<div v-for="(matches, date) in groupedMatches" :key="date">
<h3>{{ date }}</h3>
<table>
<!-- 表格内容同上 -->
</table>
</div>
交互功能实现
添加点击事件处理比赛详情展示,使用模态框或展开行显示更多信息。
<tr v-for="match in matches" @click="showDetail(match)">
<!-- 表格内容 -->
</tr>
<!-- 详情模态框 -->
<dialog v-if="selectedMatch" @click.self="selectedMatch = null">
<h4>{{ selectedMatch.teamA }} vs {{ selectedMatch.teamB }}</h4>
<p>日期: {{ selectedMatch.date }}</p>
<p>比分: {{ selectedMatch.scoreA }} - {{ selectedMatch.scoreB }}</p>
<button @click="selectedMatch = null">关闭</button>
</dialog>
methods: {
showDetail(match) {
this.selectedMatch = match;
}
}
样式优化
使用 CSS 增强表格的可读性和美观性,添加悬停效果和响应式设计。
.schedule-table {
width: 100%;
border-collapse: collapse;
}
.schedule-table th, .schedule-table td {
padding: 12px;
text-align: center;
border: 1px solid #ddd;
}
.schedule-table tr:hover {
background-color: #f5f5f5;
}
/* 响应式设计 */
@media (max-width: 600px) {
.schedule-table thead {
display: none;
}
.schedule-table tr {
display: block;
margin-bottom: 16px;
}
.schedule-table td {
display: block;
text-align: right;
}
.schedule-table td::before {
content: attr(data-label);
float: left;
font-weight: bold;
}
}
动态数据加载
对于大型赛事,可以从 API 异步加载数据,并添加加载状态。
data() {
return {
matches: [],
loading: false,
error: null
}
},
methods: {
async fetchMatches() {
this.loading = true;
try {
const response = await fetch('api/matches');
this.matches = await response.json();
} catch (err) {
this.error = err.message;
} finally {
this.loading = false;
}
}
},
created() {
this.fetchMatches();
}
<div v-if="loading">加载中...</div>
<div v-else-if="error">错误: {{ error }}</div>
<!-- 正常显示表格 -->
通过以上步骤,可以构建一个功能完整、样式美观的赛程表组件。根据实际需求,还可以添加更多功能如筛选、排序等。







