官方網站上使用自定義日歷插件是這樣給出的,沒有點擊事件,需要我們自定義去觸發事件,我們項目需求是一次獲取一個月的數據,所以在 上個月、今天、下個月這三個按鈕上添加點擊事件,當然如果需要點擊當前天添加點擊事件我代碼也有。
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:'自定義要展示的內容' }) }