发现 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) {
if (!(/^\d\d:\d\d$/.test(time1) && /^\d\d:\d\d$/.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>
成果如下:
发表回复