发现 Vant 没有提供用于选择 HH:mm 的时间范围选择器,于是手动实现一下。
// ———— RangeTimePicker.vue ————
<template>
<div>
<ActionSheet v-model:show="props.show">
<DatetimePicker
v-if="props.show && showEndTimePicker === false"
v-model="startTime"
@confirm="showEndTimePicker = true"
@cancel="onClose"
type="time"
title="开始时间"
:min-hour="0"
:max-hour="23"
/>
<DatetimePicker
v-if="props.show && showEndTimePicker"
v-model="endTime"
@confirm="timeConfirm"
@cancel="onClose(true)"
cancel-button-text="返回"
type="time"
title="结束时间"
:min-hour="0"
:max-hour="23"
/>
</ActionSheet>
</div>
</template>
<script setup lang="ts">
import { ActionSheet, DatetimePicker, Toast } from 'vant';
import { ref } from 'vue';
function compareTime(time1: string, time2: string) {
const REG = /([01]\d|2[0-3]):[0-5]\d/;
if (!(REG.test(time1) && REG.test(time2))) {
throw new Error('时间格式不合法,格式必须为:HH:mm 形式')
}
const timeNumber1 = time1.match(/\d/g)?.reduce((ac, cur) => ac += cur) || ''
const timeNumber2 = time2.match(/\d/g)?.reduce((ac, cur) => ac += cur) || ''
return timeNumber1 < timeNumber2
}
const props = defineProps({
show: {
type: Boolean,
default: false
},
times: {
type: Array,
default: ["09:00", "12:00"]
}
})
interface EmitsType {
(e: 'update:times', times: string[]): void
(e: 'update:show', show: boolean): void
}
const emit = defineEmits<EmitsType>()
const showEndTimePicker = ref(false)
const startTime = ref<string>(typeof props.times[0] === 'string' ? props.times[0] : '')
const endTime = ref<string>(typeof props.times[1] === 'string' ? props.times[1] : '')
const onClose = (isSetEndTime?: boolean) => {
if (isSetEndTime) {
showEndTimePicker.value = false
return
}
emit('update:show', false)
showEndTimePicker.value = false
}
const timeConfirm = () => {
if (!compareTime(startTime.value, endTime.value)) {
Toast("开始时间不能小于结束时间")
return
}
emit('update:times', [startTime.value, endTime.value])
onClose()
}
</script>
<style lang="less">
</style>
效果如下:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。