写项目时有一个需求,需要修改element-ui组件的日历组件,每一天都有可约/不可约的转态,且每天都要有详细的约定时间,效果图如下:
但是element日历组件提供的可操作API太少,所以这里推荐通过动态类名动态添加
// 这里的time变量就是当前时间new Date()
<el-calendar v-model="time" >
// 插槽
<template
slot="dateCell"
slot-scope="{date, data}"
>
// 里面的小盒子
<div class="wrap" :class="returnClass(data)" @click="updataTime(data)">
// 日期格式化
{{ data.day.split('-').slice(1)[1] }}
</div>
</template>
</el-calendar>
这里通过通过:class动态类名的returnClass方法将插槽传回来的data传入,酱紫方便我们在方法中进行逻辑判断,点击事件同理
css:
::v-deep .el-calendar {
.el-calendar-table td.is-selected {
.wrap {
background-color: rgb(196, 216, 254)!important;
}
}
.el-calendar-table td.is-today {
color: #000;
}
}
::v-deep .el-calendar-day {
padding: 0;
.wrap {
height: 100%;
padding: 12px;
position: relative;
}
.hasState {
background: rgb(241, 255, 238);
&::after {
width: 100%;
content: '可约';
display: block;
position: absolute;
left: 0;
text-align: center;
bottom: 10px;
color: rgb(35, 165, 0);
}
}
.noState {
background: rgb(255, 232, 232);
&::after {
width: 100%;
content: '不可约';
color: rgb(255, 27, 27);
display: block;
position: absolute;
left: 0;
text-align: center;
bottom: 10px;
}
}
}
这里通过类名伪元素的方法改变 可约/不可约 的样式和文字,稍后我们会在JS中判断具体返回那个类名。
最重要的JS:
// 动态类名
returnClass(data) {
let obj = {};
this.scheduleList.forEach(item => {
// 一层判断:如果我们数据中的item.date == data.day的话就是不可约转态 返回 noState
if(item.date === data.day) {
obj.noState = true
// 二层判断:如果item.status 为 true 表示 可约转态 将noState设为 false has State设为 true ,要么可约要么不可约
if(item.status === true) {
obj.noState = false;
obj.hasState = true;
}
}
})
// 最后将这个对象返回给class
return obj;
},