我现在想实现一个功能,根据服务器获取到的数据,修改el-date-picker的样式,当请求接口,后端服务器会返回若干日期,我希望在获取这些日期时,对el-date-picker的日期下拉框添加现实效果并回显,在数据包含的日期下面添加一个提示作用的小蓝点,请给出代码实例
时间: 2023-09-09 09:13:30 浏览: 35
好的,我们可以通过在 `el-date-picker` 下方添加一个 `el-date-picker-panel__icon` 元素,并设置其 `position: absolute` 来实现在日期下方添加小蓝点的效果。具体实现代码如下:
```html
<template>
<div>
<el-date-picker v-model="date" type="date" @change="handleChange"></el-date-picker>
<div class="el-date-picker-panel__icon" v-for="d in dates" :key="d" :style="{ left: getLeft(d) }"></div>
</div>
</template>
<script>
export default {
data() {
return {
date: '',
dates: [], // 后端返回的日期数据
pickerWidth: 0,
pickerLeft: 0,
panelWidth: 0,
panelLeft: 0
};
},
mounted() {
this.getDates(); // 获取后端返回的日期数据
this.$nextTick(() => {
this.pickerWidth = this.$refs.datePicker.$el.clientWidth;
this.pickerLeft = this.$refs.datePicker.$el.offsetLeft;
this.panelWidth = this.$refs.datePicker.$el.querySelector('.el-picker-panel').clientWidth;
this.panelLeft = this.$refs.datePicker.$el.querySelector('.el-picker-panel').offsetLeft;
});
},
methods: {
getDates() {
// 模拟后端返回的日期数据
setTimeout(() => {
this.dates = ['2022-01-01', '2022-01-05', '2022-01-10'];
}, 1000);
},
handleChange(val) {
// 处理选择日期时的回调
console.log(val);
},
getLeft(d) {
// 获取小蓝点的 left 值
const date = new Date(d);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const pickerCenter = this.pickerLeft + this.pickerWidth / 2;
const panelCenter = this.panelLeft + this.panelWidth / 2;
const distance = (year - 2022) * 365 + (month - 1) * 30 + day; // 计算日期与 2022-01-01 的天数差
const left = pickerCenter + (distance - 5) * 30 - panelCenter; // 5 表示 2022-01-01 到面板中心的日期数差
return `${left}px`;
}
}
};
</script>
<style>
.el-date-picker-panel__icon {
position: absolute;
width: 6px;
height: 6px;
border-radius: 50%;
background-color: #409EFF;
bottom: -4px;
}
</style>
```
在上述代码中,我们通过 `el-date-picker` 组件的 `mounted` 钩子函数获取到其位置和宽度信息,然后通过计算后端返回日期数据与 `2022-01-01` 的天数差,再结合 `el-date-picker` 的位置和宽度信息,计算出小蓝点的 `left` 值,最终实现了在日期下方添加小蓝点的效果。