最近再写后台管理系统时,遇到一个需求,就是需要写一个日历,然后添加放假时间的功能。

需要实现的功能有:

  1. 日历表头需要设置为当前年份的前后两年,比如今年是2022年,则年份下拉中时间为 2021、2022、2023.
  2. 选中的日期需要有特殊的样式来区分是否已选中。
    在这里插入图片描述

1.日历组件

在这里插入图片描述

2.自定义日历头部

<a-calendar
  :header-render="headerRender"
  @select="onSelect"
  :fullscreen="false"
>
  <div slot="dateCellRender" slot-scope="value" class="events">
    <template v-for="item in restDay">
      <span
        :key="item.holiday"
        class="restCls"
        v-if="moment(value).format('YYYY-MM-DD') == item.holiday"
      >
      </span>
    </template>
  </div>
</a-calendar>

上面代码中的restDay就是目前休息日的对象数组,具体可以根据实际进行调整格式。

自定义头部的代码:

headerRender({ value, type, onChange, onTypeChange }) {
  const start = 0;
  const end = 12;
  const monthOptions = [];

  const current = value.clone();
  const localeData = value.localeData();
  const months = [];
  for (let i = 0; i < 12; i++) {
    current.month(i);
    months.push(localeData.monthsShort(current));
  }

  for (let index = start; index < end; index++) {
    monthOptions.push(
      <a-select-option class="month-item" key={`${index}`}>
        {months[index]}
      </a-select-option>
    );
  }
  const month = value.month();

  const year = value.year();
  const options = [];
  for (let i = year - 1; i < year + 2; i += 1) {
    options.push(
      <a-select-option key={i} value={i} class="year-item">
        {i}
      </a-select-option>
    );
  }
  return (
    <div style={{ padding: "10px" }}>
      <a-row type="flex">
        <a-col>
          <a-select
            dropdownMatchSelectWidth={false}
            class="my-year-select"
            onChange={(newYear) => {
              const now = value.clone().year(newYear);
              onChange(now);
            }}
            value={String(year)}
          >
            {options}
          </a-select>
        </a-col>
        <a-col style="margin-left:10px;">
          <a-select
            dropdownMatchSelectWidth={false}
            value={String(month)}
            onChange={(selectedMonth) => {
              const newValue = value.clone();
              newValue.month(parseInt(selectedMonth, 10));
              onChange(newValue);
            }}
          >
            {monthOptions}
          </a-select>
        </a-col>
      </a-row>
    </div>
  );
},

上面的代码可以实现日历头部的年份下拉框数据的处理,为当前年份的前后两年。

3.选择的日期样式调整,需要用到dateCellRender插槽功能

在这里插入图片描述
对应的样式:

.restCls {
  position: relative;
  top: -10px;
  width: 28px;
  height: 28px;
  display: inline-block;
  left: 0px;
  border: 2px solid #67c23a;
}

如果日期跟restDay放假日期相对应的话,则会有上面的样式,也就是有个绿色的边框。

完成!!!

Logo

前往低代码交流专区

更多推荐