实现效果
思路
- 点击日期框下拉显示日期选项——触发visible-change——判断到最近三天的dom——js渲染红点
- 下拉显示日期选项时,顶部切换日期——触发panel-change——更新红点,重新渲染
完整代码
1、html:
<el-date-picker
style="margin-right: 20px"
type="date"
v-model="date"
format="YYYY-MM-DD"
value-format="YYYY-MM-DD"
:disabled-date="disabledDate"
@visible-change="handleVisibleChange"
@panel-change="panelChange"
@change="changeDate"
:clearable="false"
>
2、data:
data(){
return{
date: moment().format("YYYY-MM-DD")
}
}
3、method:
disabledDate(time) {
return time.getTime() > new Date();
},
handleVisibleChange(visible) {
if (visible) {
this.$nextTick(() => {
this.highlightRecentDays();
});
}
},
panelChange() {
this.$nextTick(() => {
this.highlightRecentDays();
});
},
// 设置日期选项提示圆点
highlightRecentDays() {
let dateHeader = document.querySelectorAll(".el-date-picker__header-label");
let dateHeaderList = [];
// 取当前年月
if (dateHeader) {
dateHeader.forEach(item => {
dateHeaderList.push(item.innerText.replace(/\s*/g, ""));
});
}
let availableCells = document.querySelectorAll(".available");
if (availableCells.length == 0) {
// 遍历每个不可用的单元格
const disableCells = document.querySelectorAll(".normal");
console.log("disableCells", disableCells);
if (disableCells && disableCells.length > 0) {
const existingDot = disableCells.querySelector(".yuandian");
if (existingDot) {
disableCells.removeChild(existingDot);
}
}
} else {
// 遍历每个可用的单元格
availableCells.forEach(parentCell => {
const dateCell = parentCell.querySelector(".el-date-table-cell");
if (dateCell) {
const dateTextElement = dateCell.querySelector(".el-date-table-cell__text");
let diffDays = 0;
if (dateTextElement) {
let dateText = dateTextElement.innerText.trim();
let dateStr = dateHeaderList.join("") + parseInt(dateText, 10);
let date = moment(dateStr.replace(/年/g, "-").replace(/月/g, "-")).format("YYYY-MM-DD");
let today = moment().format("YYYY-MM-DD");
const date1 = new Date(date);
const date2 = new Date(today);
const diff = Math.abs(date2 - date1);
diffDays = Math.ceil(diff / (1000 * 3600 * 24));
}
if (diffDays <= 3 && diffDays > 0) {
parentCell.style.position = "relative";
const dot = document.createElement("span");
dot.className = "yuandian";
dot.style.position = "absolute";
dot.style.left = "50%";
dot.style.top = "30px";
dot.style.width = "4px";
dot.style.height = "4px";
dot.style.transform = "translateX(-50%)";
dot.style.backgroundColor = "#1b6ac1";
dot.style.borderRadius = "50%";
parentCell.appendChild(dot);
} else {
const existingDot = parentCell.querySelector(".yuandian");
if (existingDot) {
parentCell.removeChild(existingDot);
}
}
}
});
}
}