背景:在项目开发时,有A、B两个页面,A页面是列表页,按照年与月进行搜索;B页面是详情页,按照年月日搜索,但是年月是根据每条明细进行变化的。如:该条明细是2022年1月的,详情页仅能选择2022年1月的日期。

DatePicker 代码实例

限制勾选范围为当前月份

// 限制勾选范围为当前月份
<template>
  <a-range-picker
    :value="hackValue || value"
    :disabled-date="disabledDate"  // 新增该属性
    @change="onChange"
    @openChange="onOpenChange"
    @calendarChange="onCalendarChange"
  />
</template>

<script lang="ts" setup>
import { Dayjs } from 'dayjs'

const disabledDate = (current: Dayjs) => {
  const monthStart = dayjs().startOf('month') // 当前月第一天
  const monthEnd = dayjs().endOf('month') // 当前月最后一天
  return monthStart > current || current >= monthEnd
}
</script>

限制范围为指定日期的当前月份

// 限制范围为指定日期的当前月份
<template>
  <a-range-picker
    :value="hackValue || value"
    :disabled-date="disabledDate"
    :default-picker-value="defaultPickerValue"  // 绑定初始值
  />
</template>

<script lang="ts" setup>
import { Dayjs } from 'dayjs'

const defaultPickerValue = ref<>()

const disabledDate = (current: Dayjs) => {
  const monthStart = dayjs(defaultPickerValue.value).startOf('month') // 需要在dayjs()更新传入的年月
  const monthEnd = dayjs(defaultPickerValue.value).endOf('month') // 需要在dayjs()更新传入的年月
  return monthStart > current || current >= monthEnd
}
</script>

限制选择范围仅7天(含当天)

// 限制范围为指定日期的当前月份
<template>
  <a-range-picker
    :value="hackValue || value"
    :disabled-date="disabledDate"
    :default-picker-value="defaultPickerValue"  // 绑定初始值
  />
</template>

<script lang="ts" setup>
import { Dayjs } from 'dayjs'

const defaultPickerValue = ref<>()

// 禁用时间范围
const disabledDate = (current: Dayjs) => {
  return (
    (current && current < dayjs().startOf('day')) ||
    (current && current > dayjs().add(6, 'day').endOf('day'))
  )
}
</script>

参考

Logo

前往低代码交流专区

更多推荐