vue实现赛程
Vue 实现赛程功能
在 Vue 中实现赛程功能通常需要以下几个关键步骤:
数据结构设计
赛程数据通常包含比赛时间、对阵双方、比分等信息。可以使用如下数据结构:
matches: [
{
id: 1,
date: '2023-10-15',
time: '14:00',
homeTeam: 'Team A',
awayTeam: 'Team B',
homeScore: 2,
awayScore: 1,
status: 'finished'
},
// 更多比赛...
]
组件结构
创建赛程组件时可以考虑以下结构:
<template>
<div class="schedule">
<div v-for="match in matches" :key="match.id" class="match-item">
<div class="match-time">{{ match.date }} {{ match.time }}</div>
<div class="teams">
<span class="home-team">{{ match.homeTeam }}</span>
<span class="score" v-if="match.status === 'finished'">
{{ match.homeScore }} - {{ match.awayScore }}
</span>
<span class="vs" v-else>VS</span>
<span class="away-team">{{ match.awayTeam }}</span>
</div>
<div class="match-status">{{ match.status }}</div>
</div>
</div>
</template>
样式设计
为赛程添加基本样式:
.schedule {
max-width: 800px;
margin: 0 auto;
}
.match-item {
padding: 15px;
margin-bottom: 10px;
border: 1px solid #eee;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: space-between;
}
.teams {
flex: 1;
text-align: center;
}
.score, .vs {
margin: 0 10px;
font-weight: bold;
}
.match-time, .match-status {
width: 150px;
}
数据分组
如果需要按日期分组显示赛程:
computed: {
groupedMatches() {
return this.matches.reduce((groups, match) => {
const date = match.date
if (!groups[date]) {
groups[date] = []
}
groups[date].push(match)
return groups
}, {})
}
}
动态渲染
在模板中使用分组数据:
<template>
<div class="schedule">
<div v-for="(matches, date) in groupedMatches" :key="date">
<h3>{{ date }}</h3>
<div v-for="match in matches" :key="match.id" class="match-item">
<!-- 比赛内容 -->
</div>
</div>
</div>
</template>
API 集成
从后端获取赛程数据:
async created() {
try {
const response = await axios.get('/api/matches')
this.matches = response.data
} catch (error) {
console.error('获取赛程失败:', error)
}
}
交互功能
添加点击事件查看比赛详情:
<template>
<div class="match-item" @click="showMatchDetail(match.id)">
<!-- 比赛内容 -->
</div>
</template>
<script>
methods: {
showMatchDetail(matchId) {
this.$router.push(`/match/${matchId}`)
}
}
</script>
状态管理
对于复杂应用,可以使用 Vuex 管理赛程状态:
// store/modules/schedule.js
export default {
state: {
matches: []
},
mutations: {
SET_MATCHES(state, matches) {
state.matches = matches
}
},
actions: {
async fetchMatches({ commit }) {
const response = await axios.get('/api/matches')
commit('SET_MATCHES', response.data)
}
}
}
这些步骤涵盖了 Vue 实现赛程功能的主要方面,可以根据实际需求进行调整和扩展。







