1.前言
el-calendar是elementUI的日历组件,可以非常便捷的加载一个日历视图,也可做某些自定义,稍微有点麻烦,主要是官方提供的功能较少,文档也不全,大部分需要自己定义。
2.标准样式
最基本的样式只需要几行代码实现~
<el-calendar v-model="value">
</el-calendar>
<script>
export default {
data() {
return {
value: new Date()
}
}
}
</script>
基本的日历具备以下一些功能:首先会展示当前月份日历视图,默认选中今天,上个月和下个月的日期块以灰色展示,通过点击“上个月”/“下个月”按钮,日历会相应跳转,另外点击灰色的日期块的时候也会进行相应的跳转。
3.自定义日期块内容
我们在前端展示日历视图的时候,通常都希望它有更多的标记功能和点击事件,先来看看给日期块添加标记的方法:
<el-calendar v-model="calendarValue" id="calendar">
<template slot="dateCell" slot-scope="{date, data}">
<div @click="chooseDay(data)">
<el-row>
<el-col :span="10">
<div class="calendar-day">{{ data.day.split('-').slice(2).join('-') }}//取日期的天
</div>
</el-col>
<el-col :span="4">
<div class="blue budge" v-if="dealMyDate(data.day)"></div>//加个小蓝点
</el-col>
</el-row>
</div>
</template>
</el-calendar>
dealMyDate(v) {
let res = "";
this.potDate = [
{date:"2021-02-02",hasRecord:true},
{date:"2020-02-24",hasRecord:true}
]
for(let i=0; i<this.potDate.length; i++){
if(this.potDate[i].date === v) {
res = this.potDate[i].hasRecord;
break
}
}
return res
},
.budge{
width: 10px;
height: 10px;
border-radius: 5px;
margin: 10px auto;
}
.blue{
background-color: #409eff;
}
这样就实现了在日历中某些日期块上加上了一个小蓝点,我们可以用这种方式来表示这一天有特殊事件之类的。
(可以看到此时日历我已经自定义了一些样式,没什么特别的就不放上来了)
4.自定义点击日期块的事件
上面的HTML代码中有一句: @click=“chooseDay(data)”,就是给日期块添加了一个点击事件,可以在这个事件做一些处理,我这里是分别给这个月、上个月和下个月的日期块绑定了不同的操作。
chooseDay(data){
if(data.type === "current-month"){
this.calendarStart = data.day;
this.calendarEnd = data.day;
this.tableInit(this.recordID.id);
}else if(data.type === "prev-month"){
this.prevBtn.click();
}else if(data.type === "next-month"){
this.nextBtn.click();
}
}
5.自定义右上角月份按钮
这里的操作主要用获取类名的方式给切换月份的按钮添加点击事件,并且根据项目需要,把“今天”改成了“当月”。
calendarListener(){
//修改“今天”为“当月”
let span1 = document.querySelector(".el-button--mini:not(:first-child):not(:last-child) span");
span1.innerText = '当月';
let that = this;
let newHandle = function (e) {
e.stopPropagation();
that.getCalendarTime();
that.calendarInit();
};
//上个月按钮
this.prevBtn = document.querySelector('.el-button--mini:first-child');
this.prevBtn.onclick = function (e) {
newHandle(e);
};
//下个月按钮
this.nextBtn = document.querySelector('.el-button--mini:last-child');
this.nextBtn.onclick = function (e) {
newHandle(e);
};
//本月按钮
this.thisBtn = document.querySelector('.el-button--mini:not(:first-child):not(:last-child)');
this.thisBtn.onclick = function (e) {
newHandle(e);
}
},
在绑定事件的时候,最初用了addEventListener,发现会多次进入这个事件,我猜是因为我的页面中有异步加载的数据,因此页面刷新了几次,造成了事件重复绑定,没有找到特别好的方法解决,故而换成了onclick。onclick的特点就是重复绑定时同名事件后面的会覆盖前面的。
6.其它自定义
项目中还有一个需求是统计每周完成率达标情况,达标的标成绿色,获取需要标绿的那一周,找到对应日历里的.el-calendar-table__row,来改变它的样式。
this.rowList = document.querySelectorAll(".el-calendar-table__row");
if(this.rowList){
this.rowList.forEach((value,index)=>{
if(this.weekQualified[index] === true){
value.style = "background: rgba(156, 199, 195, 17%)";
}else {
value.style = "background: rgb(255, 255, 255 )";
}
});
}