利用vue实现购票
使用 Vue 实现购票功能
项目初始化与依赖安装
使用 Vue CLI 初始化项目,安装必要依赖如 Vue Router 和 Axios:
vue create ticket-booking
cd ticket-booking
npm install vue-router axios
路由配置
在 src/router/index.js 中配置基本路由:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Booking from '../views/Booking.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/booking', component: Booking }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
票务数据管理
创建 src/store/tickets.js 管理状态:

import { reactive } from 'vue'
export const ticketStore = reactive({
availableTickets: [
{ id: 1, name: '标准票', price: 100, quantity: 50 },
{ id: 2, name: 'VIP票', price: 200, quantity: 20 }
],
cart: [],
addToCart(ticket) {
const existing = this.cart.find(item => item.id === ticket.id)
existing ? existing.quantity++ : this.cart.push({...ticket, quantity: 1})
}
})
票务列表组件
创建 src/components/TicketList.vue:
<template>
<div v-for="ticket in tickets" :key="ticket.id" class="ticket-item">
<h3>{{ ticket.name }}</h3>
<p>价格: ¥{{ ticket.price }}</p>
<p>剩余: {{ ticket.quantity }}</p>
<button @click="addToCart(ticket)">加入购物车</button>
</div>
</template>
<script>
import { ticketStore } from '../store/tickets'
export default {
computed: {
tickets() {
return ticketStore.availableTickets
}
},
methods: {
addToCart(ticket) {
ticketStore.addToCart(ticket)
}
}
}
</script>
购物车组件
创建 src/components/Cart.vue:

<template>
<div v-if="cart.length">
<h3>购物车</h3>
<div v-for="item in cart" :key="item.id">
{{ item.name }} × {{ item.quantity }} = ¥{{ item.price * item.quantity }}
</div>
<p>总价: ¥{{ total }}</p>
<button @click="checkout">结算</button>
</div>
</template>
<script>
import { ticketStore } from '../store/tickets'
export default {
computed: {
cart() {
return ticketStore.cart
},
total() {
return this.cart.reduce((sum, item) => sum + (item.price * item.quantity), 0)
}
},
methods: {
checkout() {
alert(`订单提交成功!总金额: ¥${this.total}`)
ticketStore.cart = []
}
}
}
</script>
主页面集成
在 src/views/Booking.vue 中集成组件:
<template>
<div class="booking-page">
<h2>票务预订</h2>
<TicketList />
<Cart />
</div>
</template>
<script>
import TicketList from '../components/TicketList.vue'
import Cart from '../components/Cart.vue'
export default {
components: { TicketList, Cart }
}
</script>
API 集成(可选)
创建 src/api/tickets.js 处理后端请求:
import axios from 'axios'
const api = axios.create({
baseURL: 'https://your-api-endpoint.com'
})
export const getTickets = () => api.get('/tickets')
export const createOrder = (order) => api.post('/orders', order)
样式优化
添加基础样式到 src/assets/styles.css:
.ticket-item {
border: 1px solid #ddd;
padding: 15px;
margin: 10px;
border-radius: 5px;
}
button {
background: #42b983;
color: white;
border: none;
padding: 8px 15px;
border-radius: 4px;
cursor: pointer;
}






