赞
踩
问题需求:开发过程中,对于时间选择器的月份选择,选择的值只有起始值,后端需要我将时间区间补全,以数组形式传递。例如:[‘2021-08’, ‘2022-05’],补全为[‘2021-08’, , ‘2021-09’, ‘2021-10’, ‘2021-11’, ‘2021-12’,‘2022-01’,‘2022-02’,‘2022-03’,‘2022-04’,‘2022-05’]的形式。
出现的情况有同年补全和跨年补全,方法如下:
<el-date-picker
v-model="monthsList"
type="monthrange"
clearable
@change="chooseMonths"
value-format="yyyy-MM"
start-placeholder="起始月份"
range-separator="至"
end-placeholder="结束月份"
>
</el-date-picker>
// 查询日期为时间区间,补全中间所有月份 completeTheMonths(list) { let arr = [] let nextYear = '' // let list = ['2021-08', '2022-05'] let str1 = list[0].substring(0, 4) let str2 = list[1].substring(0, 4) let num1 = list[0].substring(5, 7) let num2 = list[1].substring(5, 7) // 如果年份相等 if (str1 == str2) { arr.push(list[0]) for (let i = 1; i < 50; i++) { if (Number((Number(num1) + i + '').padStart(2, 0)) <= Number(num2)) { arr.push(str1 + '-' + (Number(num1) + i + '').padStart(2, '0')) } else { break } } } else { // let nextYear = '' // 如果年份不等 arr.push(list[0]) for (let i = 1; i < 50; i++) { if (Number((Number(num1) + i + '').padStart(2, 0)) <= Number(12)) { arr.push(str1 + '-' + (Number(num1) + i + '').padStart(2, '0')) } else { nextYear = Number(str1) + 1 break } } if (Number(nextYear) == Number(str2)) { for (let i = 1; i < 15; i++) { if (Number((Number(i) + '').padStart(2, 0)) <= Number(num2)) { arr.push(nextYear + '-' + (Number(i) + '').padStart(2, '0')) } else { break } } } else { let n = Number(str2) - Number(str1) for (let i = 0; i < n - 1; i++) { for (let j = 1; j < 13; j++) { arr.push(Number(Number(nextYear) + i) + '-' + (Number(j) + '').padStart(2, '0')) } } for (let i = 1; i < 13; i++) { if (Number((Number(i) + '').padStart(2, 0)) <= Number(num2)) { arr.push(str2 + '-' + (Number(i) + '').padStart(2, '0')) } else { break } } } } this.$nextTick((_) => { return arr }) return arr }
chooseMonths(val) {
if (val) {
this.bfmonthsList = this.completeTheMonths(val)
//bfmonthsList为补全后的时间数组
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。