vue实现选座位
实现选座位功能(Vue)
基础数据结构设计
使用二维数组表示座位布局,每个座位包含状态(可选/已选/不可选)和唯一标识符。
data() {
return {
seats: [
[
{ id: 'A1', status: 'available' },
{ id: 'A2', status: 'unavailable' }
],
[
{ id: 'B1', status: 'available' },
{ id: 'B2', status: 'available' }
]
],
selectedSeats: []
}
}
模板渲染
使用嵌套 v-for 渲染座位表格,动态绑定样式类。

<div class="seat-map">
<div v-for="(row, rowIndex) in seats" :key="rowIndex" class="seat-row">
<div
v-for="seat in row"
:key="seat.id"
:class="['seat', seat.status]"
@click="selectSeat(seat)"
>
{{ seat.id }}
</div>
</div>
</div>
样式定义
通过 CSS 类控制不同状态的视觉表现。
.seat {
width: 40px;
height: 40px;
margin: 5px;
display: inline-flex;
justify-content: center;
align-items: center;
cursor: pointer;
border: 1px solid #ccc;
}
.available { background-color: #e8f5e9; }
.unavailable { background-color: #ffcdd2; cursor: not-allowed; }
.selected { background-color: #bbdefb; }
座位选择逻辑
点击时修改座位状态并更新已选列表。

methods: {
selectSeat(seat) {
if (seat.status !== 'available') return;
const index = this.selectedSeats.findIndex(s => s.id === seat.id);
if (index >= 0) {
seat.status = 'available';
this.selectedSeats.splice(index, 1);
} else {
seat.status = 'selected';
this.selectedSeats.push(seat);
}
}
}
进阶功能实现
添加最大可选数量限制和确认按钮。
selectSeat(seat) {
if (seat.status !== 'available') return;
if (this.selectedSeats.length >= 5 && !this.selectedSeats.includes(seat)) {
alert('最多选择5个座位');
return;
}
// ...原有逻辑
}
<button
@click="confirmSelection"
:disabled="selectedSeats.length === 0"
>
确认选择 ({{ selectedSeats.length }})
</button>
服务器交互示例
提交已选座位到后端API。
async confirmSelection() {
try {
const response = await axios.post('/api/seats/book', {
seats: this.selectedSeats.map(s => s.id)
});
alert('预订成功');
} catch (error) {
alert('操作失败');
}
}






