官方网站上使用自定义日历插件是这样给出的,没有点击事件,需要我们自定义去触发事件,我们项目需求是一次获取一个月的数据,所以在 上个月、今天、下个月这三个按钮上添加点击事件,当然如果需要点击当前天添加点击事件我代码也有。
html部分:
<el-calendar v-model="timeValue" id="calendar"> <template slot="dateCell" slot-scope="{date, data}"> <!--自定义内容--> <div @click="changeTime(date,data)"> <div class="calendar-day">{{ data.day.split('-').slice(2).join('-') }}</div> <div v-for="item in calendarData"> <div v-if="(item.months).indexOf(data.day.split('-').slice(1)[0])!=-1"> <div v-if="(item.days).indexOf(data.day.split('-').slice(2).join('-'))!=-1"> <div class="is-selected">{{item.content}}</div> </div> <div v-else></div> </div> <div v-else></div> </div> </div> </template> </el-calendar>
css部分:
.div-Calendar { width: 100%; height: 100%; box-sizing: border-box; } .calendar-day { text-align: center; color: #202535; line-height: 30px; font-size: 12px; } .is-selected { color: #F8A535; font-size: 10px; margin-top: 5px; } #calendar .el-button-group>.el-button:not(:first-child):not(:last-child):after { content: '当月'; }
js代码:
created(){ this.$nextTick(() => { // 点击前一个月 let prevBtn = document.querySelector( ".el-calendar__button-group .el-button-group>button:nth-child(1)" ); prevBtn.addEventListener("click", e => { let d = new Date(this.timeValue); let resDate = d.getFullYear() + '-' + this.handleTime((d.getMonth() + 1));//2020-08 }) //点击下一个月 let nextBtn = document.querySelector( ".el-calendar__button-group .el-button-group>button:nth-child(3)" ); nextBtn.addEventListener("click", e => { let d = new Date(this.timeValue); let resDate = d.getFullYear() + '-' + this.handleTime((d.getMonth() + 1));//2020-10 }) //点击今天 let todayBtn = document.querySelector( ".el-calendar__button-group .el-button-group>button:nth-child(2)" ); todayBtn.addEventListener("click", e => { let d = new Date(this.timeValue); let resDate = d.getFullYear() + '-' + this.handleTime((d.getMonth() + 1));//2020-09 }) }); } methods:{ //处理时间 handleTime(s) { return s < 10 ? '0' + s : s }, //点击天数 changeTime(date, data) { console.log(date,data); }, }
mounted(){ this.calendarData.push({ months: [9,10],//当前月 days:[1,2,3],//天 content:'自定义要展示的内容' }) }