image.png
<template>
<div>
<el-date-picker
ref="startDateRef"
v-model="form.startDate"
type="date"
value-format="YYYY-MM-DD"
clearable
@focus="handleFocus"
class="custom-date-picker"
>
</el-date-picker>
</div>
</template>
<script setup>
import { ref, nextTick } from "vue";
const form = ref({
startDate: "",
});
const startDateRef = ref(null);
let customButton = null;
function handleFocus() {
nextTick(() => {
const panel = document.querySelector(".el-picker-panel");
if (panel) {
// 移除已存在的按钮,防止重复创建
if (customButton) {
customButton.remove();
}
customButton = document.createElement("button");
customButton.innerText = "今天";
customButton.className = "custom-button"; // 添加类名用于后续查询和移除
customButton.style.cssText = `
color: #fff;
border: none;
background: none;
font-size: 12px;
cursor: pointer;
background: #c20000;
border-radius: 4px;
margin-right: 20px;
float: right;
margin-bottom: 20px;
`;
customButton.onclick = () => {
form.value.startDate = getNowDate();
startDateRef.value.handleClose();
// 移除焦点
setTimeout(() => {
document.querySelector(".custom-date-picker input")?.blur();
}, 50);
};
panel.appendChild(customButton);
}
});
}
function getNowDate() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(
2,
"0"
)}-${String(now.getDate()).padStart(2, "0")}`;
}
</script>