ElementUI 本身没有提供年份范围选择组件,但可以通过封装两个年份选择器来实现类似的功能。以下是一个使用 Vue2 和 ElementUI 实现年份范围选择器的示例代码:
ElementUI 本身没有提供年份范围选择组件,但可以通过封装两个年份选择器来实现类似的功能。以下是一个使用 Vue2 和 ElementUI 实现年份范围选择器的示例代码:
<script>
export default {
name: 'YearRangePicker',
// 接收父组件传入的年份范围数据
props: {
value: {
type: Array,
required: true
}
},
data() {
const [startYear, endYear] = this.value
return {
startYear: startYear || '',
endYear: endYear || ''
}
},
watch: {
value: {
handler() {
const [startYear, endYear] = this.value
// 初始化自身变量,将父组件传入的年份范围设置到两个年份选择器中
this.startYear = String(startYear || '')
this.endYear = String(endYear || '')
},
deep: true
}
},
methods: {
triggerChange() {
// 将改动传回父组件
this.$emit('input', [Number(this.startYear), Number(this.endYear)])
this.$emit('change', [Number(this.startYear), Number(this.endYear)])
},
changeStartYear(val) {
// 当开始年份大于结束年份时,进行调换
if (Number(this.startYear) > Number(this.endYear)) {
this.startYear = this.endYear
this.endYear = val
}
this.triggerChange()
},
changeEndYear(val) {
if (Number(this.startYear) > Number(this.endYear)) {
this.endYear = this.startYear
this.startYear = val
}
this.triggerChange()
}
}
}
</script>
<template>
<div class="year-range-picker">
<el-date-picker
v-model="startYear"
type="year"
placeholder="选择开始年"
class="year-picker"
@change="changeStartYear"
format="yyyy 年"
value-format="yyyy"
/>
<span class="range-word">至</span>
<el-date-picker
v-model="endYear"
type="year"
placeholder="选择结束年"
class="year-picker"
@change="changeEndYear"
format="yyyy 年"
value-format="yyyy"
/>
</div>
</template>
<style scoped lang="scss">
.year-range-picker {
.range-word {
margin-left: 10px;
margin-right: 10px;
}
.year-picker {
max-width: 160px;
}
}
</style>