vue选座如何实现
Vue 选座功能实现方法
数据结构设计
选座功能的核心是座位数据的组织。通常使用二维数组或对象数组表示座位布局,例如:
seats: [
{ row: 'A', col: 1, status: 'available' }, // 可用
{ row: 'A', col: 2, status: 'selected' }, // 已选
{ row: 'B', col: 1, status: 'occupied' } // 已占用
]
或影院式布局:
rows: [
{
name: 'A',
cols: [
{ number: 1, type: 'standard', status: 'available' },
{ number: 2, type: 'vip', status: 'occupied' }
]
}
]
可视化渲染
使用 v-for 循环渲染座位,通过动态 class 绑定不同状态样式:
<div v-for="row in rows" :key="row.name" class="seat-row">
<div
v-for="col in row.cols"
:key="col.number"
:class="['seat', col.status, col.type]"
@click="selectSeat(row, col)"
>
{{ col.number }}
</div>
</div>
CSS 示例:
.seat {
width: 30px;
height: 30px;
margin: 5px;
cursor: pointer;
}
.available { background-color: #ccc; }
.selected { background-color: #4CAF50; }
.occupied { background-color: #f44336; }
.vip { border: 2px solid gold; }
交互逻辑
实现座位选择/取消的点击事件:
methods: {
selectSeat(row, col) {
if (col.status === 'occupied') return;
col.status = col.status === 'selected'
? 'available'
: 'selected';
this.updateSelectedSeats();
},
updateSelectedSeats() {
this.selectedSeats = this.rows.flatMap(row =>
row.cols.filter(col => col.status === 'selected')
);
}
}
进阶功能
-
连选限制:限制必须选择相邻座位
validateAdjacent(selectedSeats) { const rows = new Set(selectedSeats.map(s => s.row)); const cols = selectedSeats.map(s => s.col).sort(); return cols.every((col, i) => i === 0 || col === cols[i-1] + 1); } -
座位类型差异:不同座位类型显示不同价格
computed: { totalPrice() { return this.selectedSeats.reduce((sum, seat) => sum + (seat.type === 'vip' ? 50 : 30), 0); } } -
屏幕标识:添加影院屏幕标识
<div class="screen">SCREEN</div> <style> .screen { width: 80%; height: 20px; margin: 0 auto 30px; background: linear-gradient(to top, #555, #999); box-shadow: 0 0 10px rgba(0,0,0,0.5); } </style>
数据持久化
提交选座数据到后端:
async confirmSelection() {
const res = await axios.post('/api/book', {
seats: this.selectedSeats,
sessionId: this.sessionId
});
if (res.data.success) {
this.$router.push('/payment');
}
}
注意事项
- 使用 Vuex 管理复杂状态时,建议将座位数据存储在 store 中
- 移动端适配需要增加触摸事件和响应式布局
- 性能优化:大量座位渲染时建议使用虚拟滚动技术
- 可访问性:为座位添加 ARIA 标签和键盘导航支持







