vue实现座位
Vue 实现座位功能
使用 Vue 实现座位功能通常涉及动态渲染座位布局、处理选座逻辑以及状态管理。以下是实现步骤和代码示例:
基础实现方案
数据准备 定义座位数据结构,通常使用二维数组或对象数组:
data() {
return {
seats: [
[{ id: 'A1', status: 'available' }, { id: 'A2', status: 'booked' }],
[{ id: 'B1', status: 'available' }, { id: 'B2', status: 'available' }]
],
selectedSeats: []
}
}
模板渲染 使用嵌套 v-for 渲染座位网格:
<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, { selected: selectedSeats.includes(seat.id) }]"
@click="toggleSeat(seat)"
>
{{ seat.id }}
</div>
</div>
交互逻辑 实现座位选择/取消功能:
methods: {
toggleSeat(seat) {
if (seat.status !== 'available') return;
const index = this.selectedSeats.indexOf(seat.id);
if (index > -1) {
this.selectedSeats.splice(index, 1);
} else {
this.selectedSeats.push(seat.id);
}
}
}
进阶功能实现
样式处理 添加 CSS 类区分不同状态:
.seat {
width: 30px;
height: 30px;
margin: 5px;
display: inline-flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.available { background-color: #e0e0e0; }
.booked { background-color: #f44336; cursor: not-allowed; }
.selected { background-color: #4CAF50; }
可视化优化 添加屏幕和过道等剧院元素:
<div class="screen">SCREEN</div>
<div v-for="(row, i) in seats" :key="i">
<div class="row-label">Row {{ String.fromCharCode(65 + i) }}</div>
<div class="seat-row">
<!-- 座位渲染 -->
</div>
</div>
状态管理方案
对于复杂场景可使用 Vuex:
// store.js
state: {
seatMap: []
},
mutations: {
UPDATE_SEAT_STATUS(state, { id, status }) {
// 更新座位状态逻辑
}
}
性能优化 对于大规模座位渲染(如超过1000个座位):
- 使用虚拟滚动(如 vue-virtual-scroller)
- 分批加载数据
- 使用计算属性过滤可用座位
完整示例组件
<template>
<div class="seat-container">
<div class="screen">SCREEN</div>
<div v-for="(row, rowIndex) in seatLayout" :key="rowIndex" class="row-container">
<div class="row-label">{{ rowLabel(rowIndex) }}</div>
<div class="seat-row">
<div
v-for="seat in row"
:key="seat.id"
:class="seatClasses(seat)"
@click="handleSeatClick(seat)"
>
{{ seat.id.slice(-1) }}
</div>
</div>
</div>
<div class="selection-summary">
Selected: {{ selectedSeats.join(', ') }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
seatLayout: this.generateSeatMap(10, 8),
selectedSeats: []
}
},
methods: {
generateSeatMap(rows, cols) {
// 生成座位图的实现
},
rowLabel(index) {
return String.fromCharCode(65 + index);
},
seatClasses(seat) {
return {
seat: true,
[seat.status]: true,
selected: this.selectedSeats.includes(seat.id)
};
},
handleSeatClick(seat) {
if (seat.status !== 'available') return;
const index = this.selectedSeats.indexOf(seat.id);
index === -1
? this.selectedSeats.push(seat.id)
: this.selectedSeats.splice(index, 1);
}
}
}
</script>
第三方库方案
对于专业级座位选择可考虑:
- vue-seatmap:专为 Vue 开发的座位图组件
- svg-seatmap:基于 SVG 的可缩放座位图
- theaterjs:完整的剧场座位解决方案
实现要点总结:

- 合理设计数据结构反映座位布局和状态
- 使用 CSS 清晰区分不同状态的座位
- 添加无障碍访问属性(如 aria-label)
- 移动端适配触摸操作
- 考虑添加座位提示(hover 显示信息)
- 实现最大可选座位数限制等业务逻辑






