element datapicker不支持插槽,无法自定义样式,要想实现如图样式,思路如下:
给datepicker一个绝对定位,让他和自定义按钮重合,然后设置picker透明度为0即可实现
代码如下:
<template>
<div class="box">
<div
class="btn month"
:class="date == '' ? 'active' : ''"
@click="month"
>
本月
</div>
<div
class="btn date"
:class="date !== '' ? 'active' : ''"
>
{{ date == "" ? "选择时间" : date }}
</div>
<el-date-picker
v-model="value1"
class="datepicker"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
@change="change"
/>
</div>
</template>
<script>
export default {
name: 'DatePicker',
data() {
return {
value1: '',
date: ''
}
},
mounted() {
this.month()
},
methods: {
change() {
this.date = this.formatDate(this.value1[0]) + '~' + this.formatDate(this.value1[1])
this.$emit('getDate', [this.formatParamsDate(this.value1[0]) + ' 00:00:00', this.formatParamsDate(this.value1[1]) + ' 23:59:59'])
},
formatDate(date) {
const month = date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
const day = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate()
return month + '.' + day
},
formatParamsDate(date) {
const year = date.getFullYear()
const month = date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
const day = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate()
return year + '-' + month + '-' + day
},
month() {
this.date = ''
const now = this.formatParamsDate(new Date()).split('-')
this.$emit('getDate', [now[0] + '-' + now[1] + '-01' + ' 00:00:00', this.formatParamsDate(new Date()) + ' 23:59:59'])
}
}
}
</script>
<style scoped lang="scss">
.box {
background: #f2f3f5;
padding: 0.2vw;
border-radius: 0.1vw;
font-size: 0.8vw;
line-height: 1.1vw;
display: flex;
width: 8.8vw;
box-sizing: border-box;
cursor: pointer;
position: relative;
.btn {
padding: 0.1vw 0.6vw;
border-radius: 0.1vw;
background: #f2f3f5;
box-sizing: border-box;
}
.active {
background: #ffffff;
color: #409eff;
font-weight: 600;
}
.month {
width: 2.9vw;
}
.date {
width: 5.5vw;
text-align: center;
}
.datepicker {
opacity: 0;
position: absolute;
width: 5.5vw;
right: 0;
height: 16px;
}
}
</style>