Element 日期选择器改造,需求是打开选择器里面可以按日期选,按月份选,按年份选,如下图
我们要怎么去实现这个需求尼?那我们就简单粗暴一点上代码
html代码
<el-date-picker
key="date"
ref="date"
size="mini"
v-model="time"
@focus="focus"
v-if="timeType=='day'"
type="date"
placeholder="选择日期"
:picker-options="pickerOptions"
value-format="yyyy-MM-dd"
></el-date-picker>
<el-date-picker
key="month"
ref="month"
size="mini"
v-model="time"
v-if="timeType=='month'"
type="month"
@focus="focus"
placeholder="选择月份"
:picker-options="pickerOptions"
value-format="yyyy-MM"
></el-date-picker>
<el-date-picker
key="yearData"
ref="yearData"
size="mini"
v-model="time"
v-if="timeType=='yearData'"
type="year"
placeholder="选择年份"
:picker-options="pickerOptions"
value-format="yyyy"
></el-date-picker>
js代码
data () {
let _this = this // 在外面定义this ,因为在return 里面获this的指向不对
return {
time: '',
pickerOptions: {
shortcuts: [{
text: '按日期',
onClick (picker) {
_this .time = ""
_this .timeType = "day"
_this .$refs.month && _this .$refs.month.handleClose()
_this .$refs.yearData && _this .$refs.yearData.handleClose()
_this .$nextTick(() => {
_this .$refs.date.focus()
_this .$nextTick(() => {
let dom = document.getElementsByClassName('el-picker-panel__shortcut')
dom[0] ? dom[0].style.color = "#409EFF" : ""// 高亮显示
dom[1] ? dom[1].style.color = "#606266" : ""// 正常字体颜色
dom[2] ? dom[2].style.color = "#606266" : ""// 正常字体颜色
})
})
}
},
{
text: '按月份',
onClick (picker) {
_this .time = ""
_this .timeType = "month"
_this .$refs.date && _this .$refs.date.handleClose()
_this .$refs.yearData && _this .$refs.yearData.handleClose()
_this .$nextTick(() => {
_this .$refs.month.focus()
_this .$nextTick(() => {
let dom = document.getElementsByClassName('el-picker-panel__shortcut')
dom[0] ? dom[0].style.color = "#606266" : ""
dom[1] ? dom[1].style.color = "#409EFF" : ""
dom[2] ? dom[2].style.color = "#606266" : ""
})
})
}
},
{
text: '按年',
onClick (picker) {
_this .time = ""
_this .timeType = "yearData"
_this .$refs.date && _this .$refs.date.handleClose()
_this .$refs.month && _this .$refs.month.handleClose()
_this .$nextTick(() => {
_this .$refs.yearData.focus()
_this .$nextTick(() => {
let dom = document.getElementsByClassName('el-picker-panel__shortcut')
dom[0] ? dom[0].style.color = "#606266" : ""
dom[1] ? dom[1].style.color = "#606266" : ""
dom[2] ? dom[2].style.color = "#409EFF" : ""
})
})
}
}]
},
}
}
这样就实现我们的需求拉,希望能对你有帮助!