vue实现预约页面
实现预约页面的核心步骤
使用Vue CLI或Vite创建项目
通过npm create vue@latest或npm create vite@latest初始化项目,选择Vue模板。安装必要依赖如vue-router、axios(如需后端交互)和UI库(如Element Plus)。
设计页面结构
在src/views下创建预约页面组件(如Booking.vue),包含表单区域(日期选择器、时间槽、个人信息输入)和展示区域(预约规则或已约时段提示)。示例代码框架:
<template>
<div class="booking-container">
<h3>预约服务</h3>
<form @submit.prevent="handleSubmit">
<!-- 表单字段将在此添加 -->
</form>
</div>
</template>
关键功能实现
日期时间选择组件
推荐使用第三方组件如Element Plus的日期时间选择器:
<el-date-picker
v-model="selectedDate"
type="date"
placeholder="选择日期"
:disabled-date="disablePastDates"
/>
<el-time-select
v-model="selectedTime"
:picker-options="{ start: '08:00', step: '00:30', end: '18:00' }"
/>
需在script中定义selectedDate和selectedTime的响应式变量,并通过disablePastDates方法禁用过去日期。
表单验证逻辑
使用Vue的v-model绑定表单数据,配合vee-validate或原生验证:

<el-input
v-model="form.name"
:rules="[{ required: true, message: '请输入姓名' }]"
/>
在methods中定义提交处理函数:
handleSubmit() {
this.$refs.form.validate((valid) => {
if (valid) {
axios.post('/api/bookings', this.form)
.then(response => alert('预约成功'))
}
})
}
数据交互与状态管理
API请求封装
创建src/api/booking.js封装预约相关请求:
import axios from 'axios'
export const createBooking = (data) =>
axios.post('/bookings', data)
Pinia/Vuex状态管理(可选)
对于复杂场景,可用Pinia管理预约状态:

// stores/booking.js
export const useBookingStore = defineStore('booking', {
state: () => ({
bookings: []
}),
actions: {
async fetchBookings() {
this.bookings = await getBookings()
}
}
})
样式优化与响应式
移动端适配
通过CSS媒体查询确保移动端体验:
@media (max-width: 768px) {
.booking-container {
padding: 10px;
}
.el-date-picker {
width: 100%;
}
}
加载状态与错误处理
在提交时显示加载状态:
<el-button
:loading="isSubmitting"
@click="handleSubmit"
>提交预约</el-button>
通过try/catch处理网络错误,使用ElMessage显示提示。
完整示例组件结构
<script setup>
import { ref } from 'vue'
import { createBooking } from '@/api/booking'
const form = ref({
date: '',
time: '',
name: '',
phone: ''
})
const isSubmitting = ref(false)
const handleSubmit = async () => {
isSubmitting.value = true
try {
await createBooking(form.value)
ElMessage.success('预约成功')
} catch (error) {
ElMessage.error(error.message)
} finally {
isSubmitting.value = false
}
}
</script>






