vue实现购票
Vue 实现购票功能
数据结构设计
购票功能通常需要以下数据结构:
- 场次信息(时间、地点、价格)
- 座位信息(可选座位、已售座位)
- 用户订单信息
示例数据结构:
data() {
return {
showInfo: {
id: 1,
name: '演唱会',
time: '2023-12-25 19:30',
venue: '北京国家体育场',
price: 380
},
seats: [
{ id: 'A1', status: 'available' },
{ id: 'A2', status: 'sold' },
// 更多座位...
],
selectedSeats: [],
orderInfo: {
name: '',
phone: '',
email: ''
}
}
}
座位选择组件
创建可交互的座位图组件:
<template>
<div class="seat-map">
<div
v-for="seat in seats"
:key="seat.id"
:class="['seat', seat.status]"
@click="selectSeat(seat)"
>
{{ seat.id }}
</div>
</div>
</template>
<script>
export default {
methods: {
selectSeat(seat) {
if (seat.status === 'available') {
const index = this.selectedSeats.findIndex(s => s.id === seat.id)
if (index === -1) {
this.selectedSeats.push(seat)
} else {
this.selectedSeats.splice(index, 1)
}
}
}
}
}
</script>
<style>
.seat {
width: 30px;
height: 30px;
margin: 5px;
display: inline-flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.available { background-color: #4CAF50; }
.sold { background-color: #f44336; cursor: not-allowed; }
.selected { background-color: #FFC107; }
</style>
订单表单验证
实现表单验证确保用户输入有效信息:
methods: {
validateForm() {
if (!this.orderInfo.name) {
alert('请输入姓名')
return false
}
if (!/^1[3-9]\d{9}$/.test(this.orderInfo.phone)) {
alert('请输入正确的手机号')
return false
}
if (!this.selectedSeats.length) {
alert('请选择至少一个座位')
return false
}
return true
}
}
提交订单
与后端API交互提交订单:
methods: {
async submitOrder() {
if (!this.validateForm()) return
try {
const response = await axios.post('/api/orders', {
showId: this.showInfo.id,
seats: this.selectedSeats.map(s => s.id),
customerInfo: this.orderInfo
})
if (response.data.success) {
this.$router.push(`/order/${response.data.orderId}`)
}
} catch (error) {
console.error('订单提交失败:', error)
alert('订单提交失败,请重试')
}
}
}
订单状态管理
使用Vuex管理全局订单状态:
// store/modules/order.js
export default {
state: {
currentOrder: null,
orderHistory: []
},
mutations: {
SET_CURRENT_ORDER(state, order) {
state.currentOrder = order
state.orderHistory.push(order)
}
},
actions: {
async createOrder({ commit }, orderData) {
const response = await axios.post('/api/orders', orderData)
commit('SET_CURRENT_ORDER', response.data)
return response.data
}
}
}
支付集成
集成第三方支付接口:
methods: {
async proceedToPayment() {
const paymentData = {
orderId: this.order.id,
amount: this.order.total,
paymentMethod: 'wechat'
}
try {
const response = await axios.post('/api/payment', paymentData)
if (response.data.paymentUrl) {
window.location.href = response.data.paymentUrl
}
} catch (error) {
console.error('支付处理失败:', error)
}
}
}
响应式布局
确保购票页面在不同设备上正常显示:
@media (max-width: 768px) {
.seat-map {
grid-template-columns: repeat(5, 1fr);
}
.order-form {
flex-direction: column;
}
}






