效果圖
組件代碼
<template>
<div class="yearRange">
<el-date-picker class="picker-first" v-model="start" value-format="YYYY" @change="val => onDateChange(0, val)"
:picker-options="pickerOptionsStart" :placeholder="startPlaceholder" type="year">
</el-date-picker>
<div class="devideLine">——</div>
<el-date-picker class="picker-first" v-model="end" value-format="YYYY" @change="val => onDateChange(1, val)"
:picker-options="pickerOptionsEnd" :placeholder="startPlaceholder" type="year">
</el-date-picker>
</div>
</template>
<script>
import { ref } from "vue";
export default {
name: "YearRangePicker",
setup(props, { emit }) {
const start = ref(''), end = ref('')
return {
start, end,
pickerOptionsStart: {
disabledDate(date) {
console.log(date)
return false
},
},
pickerOptionsEnd: {
disabledDate(date) {
console.log(date)
return false
},
},
onDateChange(index, val) {
if (!val) { //一清都清
start.value = ''; end.value = ''
return
}
switch (index) {
case 0:
if (!end.value || (end.value / 1 < val / 1)) {
end.value = val
}
break;
case 1:
if (!start.value || (start.value / 1 > val / 1)) {
start.value = val
}
}
emit('update:value', [start.value, end.value])
// if(index===0){
// if(!end.value){
// }
// }
}
}
},
watch: {
value: {
handler(newVal, oldValue) {
if (newVal) {
this.start = newVal[0]
this.end = newVal[1]
}
},
immediate: true
},
},
props: {
value: {
type: Array,
default: []
},
startPlaceholder: {
type: String,
default: '請選擇開始時間'
},
endPlaceholder: {
type: String,
default: '請選擇結(jié)束時間'
}
},
methods: {
},
}
</script>
<style scoped lang="scss">
.yearRange {
display: flex;
align-items: center;
.devideLine {
padding: 0 8px;
color: #999;
transform: scale(.6);
}
}
</style>
頁面內(nèi)引用
<yearRangePicker v-model:value="yearRange" start-placeholder="開始年份"
end-placeholder="結(jié)束年份"
/>
代碼中的 value-format:'YYYY',YYYY為大寫笤虫,部分項(xiàng)目中可能會導(dǎo)致無法選擇時間,將其改為yyyy即可