当前位置:首页 > VUE

vue实现选座位

2026-03-28 20:03:01VUE

实现选座位功能(Vue)

基础数据结构设计

使用二维数组表示座位布局,每个座位包含状态(可选/已选/不可选)和唯一标识符。

data() {
  return {
    seats: [
      [
        { id: 'A1', status: 'available' },
        { id: 'A2', status: 'unavailable' }
      ],
      [
        { id: 'B1', status: 'available' },
        { id: 'B2', status: 'available' }
      ]
    ],
    selectedSeats: []
  }
}

模板渲染

使用嵌套 v-for 渲染座位表格,动态绑定样式类。

vue实现选座位

<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; }

座位选择逻辑

点击时修改座位状态并更新已选列表。

vue实现选座位

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('操作失败');
  }
}

标签: 座位vue
分享给朋友:

相关文章

vue实现$.extend

vue实现$.extend

Vue 实现类似 jQuery 的 $.extend 功能 在 Vue 中实现类似 jQuery 的 $.extend 功能,可以通过多种方式完成。$.extend 主要用于合并多个对象的属性,Vue…

vue diff实现

vue diff实现

Vue Diff 算法实现原理 Vue 的虚拟 DOM Diff 算法(即 patch 过程)是其高效渲染的核心,主要通过对比新旧虚拟节点的差异,最小化 DOM 操作。以下是关键实现要点: 同层级比…

vue computed实现

vue computed实现

计算属性的基本用法 在Vue中,计算属性通过computed选项定义,用于声明依赖于其他属性的动态值。计算属性基于它们的依赖进行缓存,只有依赖发生变化时才会重新计算。 new Vue({ dat…

vue实现按钮

vue实现按钮

Vue 实现按钮的方法 使用原生 HTML 按钮 在 Vue 模板中可以直接使用 HTML 的 <button> 元素,通过 v-on 或 @ 绑定点击事件。 <template&…

实现vue message

实现vue message

实现 Vue 消息提示组件 创建 Message 组件 在 src/components 目录下创建 Message.vue 文件,内容如下: <template> <tran…

vue实现联动

vue实现联动

Vue 实现联动效果 联动效果通常指多个组件或表单元素之间相互影响,例如选择省份后动态加载城市列表。Vue 提供了多种方式实现联动,包括数据绑定、计算属性、侦听器等。 数据驱动联动 通过 Vue 的…