Skip to content

Calendar 日历

介绍

日历组件用于选择日期或日期区间。

引入

通过以下方式来引入组件。

js
import { createApp } from 'vue';
import { Calendar } from '@szhn/dh-design-mobile';

const app = createApp();
app.use(Calendar);

代码演示

选择切换模式

默认所有月份将以平铺方式展示,不显示切换按钮,当月份过多时可能会影响页面交互性能。可以通过设置 switch-mode 属性,展示年月切换按钮。

html
<van-calendar v-model:show="show" switch-mode="year-month" />

选择单个日期

下面演示了结合单元格来使用日历组件的用法,日期选择完成后会触发 confirm 事件。

html
<van-cell title="选择单个日期" :value="date" @click="show = true" />
<van-calendar v-model:show="show" @confirm="onConfirm" />
js
import { ref } from 'vue';

export default {
  setup() {
    const date = ref('');
    const show = ref(false);

    const formatDate = (date) => {
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    };
    const onConfirm = (value) => {
      show.value = false;
      date.value = formatDate(value);
    };

    return {
      date,
      show,
      onConfirm,
    };
  },
};

选择多个日期

设置 typemultiple 后可以选择多个日期,此时 confirm 事件返回的 date 为数组结构,数组包含若干个选中的日期。

html
<van-cell title="选择多个日期" :value="text" @click="show = true" />
<van-calendar v-model:show="show" type="multiple" @confirm="onConfirm" />
js
import { ref } from 'vue';

export default {
  setup() {
    const text = ref('');
    const show = ref(false);

    const onConfirm = (dates) => {
      show.value = false;
      text.value = `选择了 ${dates.length} 个日期`;
    };

    return {
      text,
      show,
      onConfirm,
    };
  },
};

选择日期区间

设置 typerange 后可以选择日期区间,此时 confirm 事件返回的 date 为数组结构,数组第一项为开始时间,第二项为结束时间。

html
<van-cell title="选择日期区间" :value="date" @click="show = true" />
<van-calendar v-model:show="show" type="range" @confirm="onConfirm" />
js
import { ref } from 'vue';

export default {
  setup() {
    const date = ref('');
    const show = ref(false);

    const formatDate = (date) => `${date.getMonth() + 1}/${date.getDate()}`;
    const onConfirm = (values) => {
      const [start, end] = values;
      show.value = false;
      date.value = `${formatDate(start)} - ${formatDate(end)}`;
    };

    return {
      date,
      show,
      onConfirm,
    };
  },
};

Tips: 默认情况下,日期区间的起止时间不能为同一天,可以通过设置 allow-same-day 属性来允许选择同一天。

快捷选择

show-confirm 设置为 false 可以隐藏确认按钮,这种情况下选择完成后会立即触发 confirm 事件。

html
<van-calendar v-model:show="show" :show-confirm="false" />

主色样式

默认使用 tokens 主色,对选中日期、日期区间和底部按钮生效。业务使用时不需要为了匹配设计稿单独传颜色。

html
<van-calendar v-model:show="show" type="range" />

自定义日期范围

通过 min-datemax-date 定义日历的范围。

html
<van-calendar v-model:show="show" :min-date="minDate" :max-date="maxDate" />
js
import { ref } from 'vue';

export default {
  setup() {
    const show = ref(false);

    return {
      show,
      minDate: new Date(2010, 0, 1),
      maxDate: new Date(2010, 0, 31),
    };
  },
};

自定义按钮文字

通过 confirm-text 设置按钮文字,通过 confirm-disabled-text 设置按钮禁用时的文字。

html
<van-calendar
  v-model:show="show"
  type="range"
  confirm-text="完成"
  confirm-disabled-text="请选择结束时间"
/>

自定义日期文案

通过传入 formatter 函数来对日历上每一格的内容进行格式化。

html
<van-calendar v-model:show="show" type="range" :formatter="formatter" />
js
export default {
  setup() {
    const formatter = (day) => {
      const month = day.date.getMonth() + 1;
      const date = day.date.getDate();

      if (month === 5) {
        if (date === 1) {
          day.topInfo = '劳动节';
        } else if (date === 4) {
          day.topInfo = '青年节';
        } else if (date === 11) {
          day.text = '今天';
        }
      }

      if (day.type === 'start') {
        day.bottomInfo = '入住';
      } else if (day.type === 'end') {
        day.bottomInfo = '离店';
      }

      return day;
    };

    return {
      formatter,
    };
  },
};

自定义弹出位置

通过 position 属性自定义弹出层的弹出位置,可选值为 topleftright

html
<van-calendar v-model:show="show" :round="false" position="right" />

日期区间最大范围

选择日期区间时,可以通过 max-range 属性来指定最多可选天数,选择的范围超过最多可选天数时,会弹出相应的提示文案。

html
<van-calendar type="range" :max-range="3" />

自定义周起始日

通过 first-day-of-week 属性设置一周从哪天开始。

html
<van-calendar first-day-of-week="1" />

平铺展示

poppable 设置为 false,日历会直接展示在页面内,而不是以弹层的形式出现。

html
<van-calendar
  title="日历"
  :poppable="false"
  :show-confirm="false"
  :style="{ height: '500px' }"
/>

API

Props

参数说明类型默认值
type选择类型:
single 表示选择单个日期,
multiple 表示选择多个日期,
range 表示选择日期区间
stringsingle
switch-mode v4.9.0切换模式:
none 平铺展示所有月份,不展示切换按钮,
month 支持按月切换,展示上个月/下个月按钮,
year-month 支持按年切换,也支持按月切换,展示上一年/下一年,上个月/下个月按钮
stringnone
title日历标题string日期选择
color主题色,默认已接入 tokens 主色stringtokens 主色
min-date可选择的最小日期Dateswitch-modenone 时为当前日期
max-date可选择的最大日期Dateswitch-modenone 时为当前日期的六个月后
default-date默认选中的日期,typemultiplerange 时为数组,传入 null 表示默认不选择Date | Date[] | null今天
row-height日期行高number | string64
formatter日期格式化函数(day: Day) => Day-
poppable是否以弹层的形式展示日历booleantrue
lazy-render是否只渲染可视区域的内容booleantrue
show-mark是否显示月份背景水印booleantrue
show-title是否展示日历标题booleantrue
show-subtitle是否展示日历副标题(年月)booleantrue
show-confirm是否展示确认按钮booleantrue
readonly是否为只读状态,只读状态下不能选择日期booleanfalse
confirm-text确认按钮的文字string确认
confirm-disabled-text确认按钮处于禁用状态时的文字string确认
first-day-of-week设置周起始日0-60

Calendar Poppable Props

当 Calendar 的 poppabletrue 时,支持以下 props:

参数说明类型默认值
v-model:show是否显示日历弹窗booleanfalse
position弹出位置,可选值为 top right leftstringbottom
round是否显示圆角弹窗booleantrue
close-on-popstate是否在页面回退时自动关闭booleantrue
close-on-click-overlay是否在点击遮罩层后关闭booleantrue
safe-area-inset-top是否开启顶部安全区适配booleanfalse
safe-area-inset-bottom是否开启底部安全区适配booleantrue
teleport指定挂载的节点,等同于 Teleport 组件的 to 属性string | Element-

Calendar Range Props

当 Calendar 的 typerange 时,支持以下 props:

参数说明类型默认值
max-range日期区间最多可选天数number | string无限制
range-prompt范围选择超过最多可选天数时的提示文案string最多选择 xx 天
show-range-prompt范围选择超过最多可选天数时,是否展示提示文案booleantrue
allow-same-day是否允许日期范围的起止时间为同一天booleanfalse

Calendar Multiple Props

当 Calendar 的 typemultiple 时,支持以下 props:

参数说明类型默认值
max-range日期最多可选天数number | string无限制
range-prompt选择超过最多可选天数时的提示文案string最多选择 xx 天

Day 数据结构

日历中的每个日期都对应一个 Day 对象,通过formatter属性可以自定义 Day 对象的内容

键名说明类型
date日期对应的 Date 对象Date
type日期类型,可选值为 selectedstartmiddleenddisabledstart-endmultiple-selectedmultiple-middleplaceholderstring
text中间显示的文字string
topInfo上方的提示信息string
bottomInfo下方的提示信息string
className额外类名string

Events

事件名说明回调参数
select点击并选中任意日期时触发value: Date | Date[]
confirm日期选择完成后触发,若 show-confirmtrue,则点击确认按钮后触发value: Date | Date[]
open打开弹出层时触发-
close关闭弹出层时触发-
opened打开弹出层且动画结束后触发-
closed关闭弹出层且动画结束后触发-
unselect当日历组件的 typemultiple 时,取消选中日期时触发value: Date
month-show当某个月份进入可视区域时触发(switch-modenone 时生效){ date: Date, title: string }
over-range范围选择超过最多可选天数时触发-
click-subtitle点击日历副标题时触发event: MouseEvent
click-disabled-date v4.7.0点击禁用日期时触发value: Date | Date[]
click-overlay v4.9.16点击遮罩层时触发event: MouseEvent
panel-change日历面板切换时触发(switch-mode 不为 none 时生效){ date: Date }

Slots

名称说明参数
title自定义标题-
subtitle自定义日历副标题{ text: string, date?: Date }
month-title v4.0.9自定义每个月份的小标题{ text: string, date: Date }
footer自定义底部区域内容-
confirm-text自定义确认按钮的内容{ disabled: boolean }
top-info自定义日期上方的提示信息day: Day
bottom-info自定义日期下方的提示信息day: Day
text自定义日期内容day: Day
prev-month自定义上个月按钮{ disabled: boolean }
prev-year自定义上一年按钮{ disabled: boolean }
next-month自定义下个月按钮{ disabled: boolean }
next-year自定义下一年按钮{ disabled: boolean }

方法

通过 ref 可以获取到 Calendar 实例并调用实例方法,详见组件实例方法

方法名说明参数返回值
reset将选中的日期重置到指定日期,未传参时会重置到默认日期date?: Date | Date[]-
scrollToDate滚动到某个日期date: Date-
getSelectedDate获取选中的日期-Date | Date[] | null

类型定义

组件导出以下类型定义:

ts
import type {
  CalendarSwitchMode,
  CalendarType,
  CalendarProps,
  CalendarDayItem,
  CalendarDayType,
  CalendarInstance,
} from '@szhn/dh-design-mobile';

CalendarInstance 是组件实例的类型,用法如下:

ts
import { ref } from 'vue';
import type { CalendarInstance } from '@szhn/dh-design-mobile';

const calendarRef = ref<CalendarInstance>();

calendarRef.value?.reset();

主题定制

样式变量

组件提供了下列 CSS 变量,可用于自定义样式,使用方法请参考 ConfigProvider 组件

名称默认值描述
--van-calendar-backgroundvar(--dh-mobile-color-surface)日历的背景色
--van-calendar-popup-height76%弹出层的高度
--van-calendar-header-shadownone日历标题的阴影
--van-calendar-header-title-height44px日历标题的高度
--van-calendar-header-title-font-sizevar(--dh-mobile-font-size-base)日历标题的字体大小
--van-calendar-header-subtitle-font-sizevar(--dh-mobile-font-size-base)日历副标题的字体大小
--van-calendar-header-action-width32px标题操作按钮的宽度
--van-calendar-header-action-colorvar(--dh-mobile-color-primary)标题操作按钮的颜色
--van-calendar-header-action-disabled-colorvar(--dh-mobile-color-text-disabled)标题操作按钮禁用状态下的颜色
--van-calendar-weekdays-height28px星期行的高度
--van-calendar-weekdays-font-sizevar(--dh-mobile-font-size-xs)星期行的字体大小
--van-calendar-month-title-font-sizevar(--dh-mobile-font-size-base)月份标题的字体大小
--van-calendar-month-mark-colortransparent月份水印的颜色
--van-calendar-month-mark-font-size160px月份水印的字体大小
--van-calendar-day-height50px日期格的高度
--van-calendar-day-font-sizevar(--dh-mobile-font-size-xs)日期格的字体大小
--van-calendar-day-margin-bottom0日期格的下外边距
--van-calendar-day-disabled-colorvar(--dh-mobile-color-text-disabled)禁用状态下日期格的颜色
--van-calendar-range-edge-colorvar(--van-white)区间起止日期的文字颜色
--van-calendar-range-edge-backgroundvar(--dh-mobile-color-primary)区间起止日期的背景色
--van-calendar-range-middle-colorvar(--dh-mobile-color-primary)区间中间日期的文字颜色
--van-calendar-range-middle-backgroundcolor-mix(in srgb, var(--dh-mobile-color-primary) 12%, transparent)区间中间日期的背景色
--van-calendar-range-middle-background-opacity0.12区间中间日期背景色的透明度
--van-calendar-selected-day-size36px选中日期的尺寸
--van-calendar-selected-day-colorvar(--van-white)选中日期的文字颜色
--van-calendar-selected-day-backgroundvar(--dh-mobile-color-primary)选中日期的背景色
--van-calendar-info-font-sizevar(--dh-mobile-font-size-mini)日期提示信息的字体大小
--van-calendar-info-line-heightvar(--dh-mobile-line-height-mini)日期提示信息的行高
--van-calendar-confirm-button-height36px确认按钮的高度
--van-calendar-confirm-button-margin12px 0 16px确认按钮的外边距
--van-calendar-confirm-button-radius4px确认按钮的圆角

常见问题

如何在 formatter 中使用异步返回的数据?

如果需要在 formatter 中使用异步返回的数据,可以使用计算属性动态创建 formatter 函数,示例如下:

js
const asyncData = ref();

const formatter = computed(() => {
  if (!asyncData.value) {
    return (day) => day;
  }
  return (day) => {
    day.bottomInfo = asyncData.value;
    return day;
  };
});

setTimeout(() => {
  asyncData.value = '后端文案';
}, 3000);

在 iOS 系统上初始化组件失败?

如果你遇到了在 iOS 上无法渲染组件的问题,请确认在创建 Date 对象时没有使用new Date('2020-01-01')这样的写法,iOS 不支持以中划线分隔的日期格式,正确写法是new Date('2020/01/01')

对此问题的详细解释:stackoverflow

或者,你应该采用一种在各个系统和浏览器上兼容性更好的写法:new Date(2020, 0, 1),但是需要注意的是,月份是从 0 开始的。