vue实现车次信息
Vue 实现车次信息功能
数据结构设计
车次信息通常包含车次编号、出发站、到达站、出发时间、到达时间、历时、座位类型及价格等字段。建议使用如下数据结构:
trainList: [
{
trainNo: 'G1234',
from: '北京',
to: '上海',
departTime: '08:00',
arriveTime: '12:30',
duration: '4小时30分',
seats: [
{ type: '二等座', price: 553 },
{ type: '一等座', price: 933 }
]
}
]
组件化开发
创建独立的车次信息组件(TrainItem.vue):
<template>
<div class="train-item">
<div class="train-header">
<span class="train-no">{{ data.trainNo }}</span>
<span class="train-route">{{ data.from }} - {{ data.to }}</span>
</div>
<div class="train-time">
<span>{{ data.departTime }}</span>
<span class="duration">{{ data.duration }}</span>
<span>{{ data.arriveTime }}</span>
</div>
<div class="train-seats">
<div v-for="seat in data.seats" :key="seat.type" class="seat-item">
<span>{{ seat.type }}</span>
<span>¥{{ seat.price }}</span>
</div>
</div>
</div>
</template>
数据获取与渲染
通过API获取数据并在父组件中渲染:
export default {
data() {
return {
trains: []
}
},
async created() {
try {
const res = await axios.get('/api/trains')
this.trains = res.data
} catch (error) {
console.error('获取车次数据失败', error)
}
}
}
样式优化
使用CSS Grid布局实现响应式设计:
.train-item {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
gap: 16px;
padding: 12px;
border-bottom: 1px solid #eee;
}
.train-time {
display: flex;
justify-content: space-between;
align-items: center;
}
.duration {
color: #999;
font-size: 0.9em;
}
.seat-item {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
}
交互功能增强
添加车次筛选和排序功能:

computed: {
filteredTrains() {
return this.trains.filter(train => {
return train.from.includes(this.searchQuery) ||
train.to.includes(this.searchQuery) ||
train.trainNo.includes(this.searchQuery)
}).sort((a, b) => {
if (this.sortBy === 'time') {
return a.departTime.localeCompare(b.departTime)
} else if (this.sortBy === 'price') {
return a.seats[0].price - b.seats[0].price
}
return 0
})
}
}
注意事项
- 对于大量车次数据,建议实现分页或虚拟滚动
- 时间显示应考虑时区转换
- 价格信息应支持货币格式化
- 移动端需优化触摸交互体验
- 可添加车次状态标识(如正点、晚点等)






