【study】element-Calendar日历自定义

338 阅读1分钟

image.png

1. 日历组件,根据后端返回的值,渲染背景色,类似于下图:

image.png

2.js的setMonth()函数某些月份得到多一个月的问题
  • new Date之后,某些月份不满足有31天,就会出现这个问题
  • 解决办法:new Date()之后立刻调用setDate(1)把日期设置为1号,后面的setMonth()、setDate()操作正常:
  • new Date((new Date().setDate(1))).setMonth(+dataMonth - 1) // dataMonth是月份,数字几
<el-col :span="24">
    <Calendar v-model="calendarValue[index]">
      <template slot="dateCell" slot-scope="{date, data}">
         <p v-if="orderDateListObj[index] && orderDateListObj[index][data.day]" class="bgColor" >
             {{ data.day.split('-').slice(2).join('-') }}
         </p>
         <p v-else>
             {{ data.day.split('-').slice(2).join('-') }}
         </p>
       </template>
    </Calendar>
</el-col>
data() {
     return {
          calendarValue: [new Date()], // 如果返回的不是本月的日历时间,直接跳到对应的当月
        };
    },
computed: {
     orderDateListObj() {
          const res = [];
          this.orderDateList.forEach((i) => {
              const dateArray = i.reduce((prev, next) => {
                    const value = formatTime(next, 'yyyy-MM-dd'); // 上面需要这种格式来进行渲染,将接口返回的数据进行处理
                    prev[`${value}`] = value;
                    return prev;
                }, {});
                res.push(dateArray);
            });
            return res;
        },
    },
methods: {
   getDate() {
            const configList = 入参
            if (configList.length > 0) {
                this.$hPost('/xxxx', { configList }).then((res) => {
                    this.orderDateList = [];
                    this.calendarValue = [];
                    res.forEach((i) => {
                        this.orderDateList.push(i.orderDateList); // 返回的所有数据
                        const dataMonth = new Date(i.orderDateList[0]).getMonth() + 1; // 返回的月份
                        const nowMonth = new Date(new Date()).getMonth() + 1; // 本月
                        if (dataMonth > nowMonth) {
                            this.calendarValue.push(new Date((new Date().setDate(1))).setMonth(+dataMonth - 1));
                        } else {
                            this.calendarValue.push(new Date());
                        }
                    });
                });
            }
        },
}