index.vue 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <template>
  2. <a-range-picker
  3. v-model:value="rangeTimes"
  4. :show-time="props.showTime"
  5. :valueFormat="props.valueFormat"
  6. :presets="props.rangePresets"
  7. />
  8. </template>
  9. <script setup lang="ts">
  10. import { computed } from 'vue'
  11. import dayjs, { type Dayjs } from 'dayjs'
  12. defineOptions({
  13. name: 'rangePicker',
  14. })
  15. type RangeValue = [Dayjs, Dayjs]
  16. interface Props {
  17. start: string | Dayjs // 开始时间
  18. end: string | Dayjs // 结束时间
  19. showTime?: boolean // 是否显示时间选择器
  20. valueFormat?: string // 时间格式
  21. rangePresets?: {
  22. label: string
  23. value: RangeValue
  24. }[]
  25. }
  26. const emit = defineEmits<{
  27. (e: 'update:start', value: string): void
  28. (e: 'update:end', value: string): void
  29. }>()
  30. const props = withDefaults(defineProps<Props>(), {
  31. start: '',
  32. end: '',
  33. showTime: false,
  34. valueFormat: 'YYYY-MM-DD', // 时间格式 YYYY-MM-DD HH:mm:ss
  35. rangePresets: () => [
  36. { label: '今天', value: [dayjs().startOf('day'), dayjs().endOf('day')] },
  37. { label: '最近7天', value: [dayjs().add(-6, 'd').startOf('day'), dayjs().endOf('day')] },
  38. { label: '最近14天', value: [dayjs().add(-13, 'd').startOf('day'), dayjs().endOf('day')] },
  39. { label: '最近30天', value: [dayjs().add(-29, 'd').startOf('day'), dayjs().endOf('day')] },
  40. { label: '最近90天', value: [dayjs().add(-89, 'd').startOf('day'), dayjs().endOf('day')] },
  41. ],
  42. })
  43. const rangeTimes = computed({
  44. get: () => {
  45. if (props.start && props.end) {
  46. const isValidRange = [props.start, props.end].every((v) => dayjs(v).isValid())
  47. return isValidRange
  48. ? [
  49. dayjs.isDayjs(props.start) ? props.start : dayjs(props.start),
  50. dayjs.isDayjs(props.end) ? props.end : dayjs(props.end),
  51. ]
  52. : undefined
  53. }
  54. return undefined
  55. },
  56. set: (val: RangeValue | undefined) => {
  57. if (Array.isArray(val) && val.length === 2) {
  58. const start = dayjs(val[0])
  59. const end = dayjs(val[1])
  60. const format = (d: Dayjs) => {
  61. const date = dayjs(d)
  62. return date.isValid() ? date.format(props.valueFormat) : ''
  63. }
  64. emit('update:start', start.isValid() ? format(val[0]) : '')
  65. emit('update:end', end.isValid() ? format(val[1]) : '')
  66. } else {
  67. emit('update:start', '')
  68. emit('update:end', '')
  69. }
  70. },
  71. })
  72. </script>
  73. <style scoped lang="less"></style>