需求来自 根据时间和日周月的选择规则 动态绘制Echarts
此需求X轴完全由前端进行绘制 数据库只给Y轴的数据 所以我们根据开始时间和结束时间生成X轴
methods:{
//日周月的点击事件 触发此事件生成X轴 this.timeData为开始时间和结束时间的事件对象
getEchartXData(index) {
switch (index) {
case 0:
return this.xData = this.getDateDayAll(this.timeData)
case 1:
return this.xData = this.intervalWeek(this.timeData)
case 2:
return this.xData = this.intervalMonth(this.timeData)
}
},
// 两个时间段以日为单位的时间
getDateDayAll({ startTime, endTime }) {
const allDaysList = [];
const SDate = moment(startTime);
const EDate = moment(endTime);
allDaysList.push(SDate.format('YYYY-MM-DD')); //追加第一天
while (SDate.add(1, 'days').isBefore(EDate)) {
// 往结束前一天追溯 循环新增到数组内
allDaysList.push(SDate.format('YYYY-MM-DD'));
}
allDaysList.push(EDate.format('YYYY-MM-DD')); //追加最后一天
return allDaysList;
},
// 两个时间段以周为单位的时间
getDateWeekAll({ startTime, endTime }) {
const SDate = moment(startTime);
const EDate = moment(endTime);
const allWeekList = [];
while (SDate.add(1, 'days').isBefore(EDate)) {
//此方法获取的是已年份开头的在当年的自然周 如2021-01 2021-02
//startOf('weeks')配合使用此方法是为了获取年初的日期更为准确 因为2021年1月1日如果不是周一的话,那么他就应该输入2020年的最后一周而不应该是2021年的第一周
allWeekList.push(moment(SDate.format('YYYY-MM-DD')).startOf('weeks').format('YYYY') + '-' + (SDate.format('WW')))
}
return Array.from(new Set(allWeekList)) || []
},
// 两个时间段以月为单位的时间
getDateMonthAll({ startTime, endTime }) {
const SDate = moment(startTime);
const EDate = moment(endTime);
const allMonthList = []; // 接收所有年份和月份的数组
while (EDate > SDate || SDate.format('M') === EDate.format('M')) {
allMonthList.push(SDate.format('YYYY-MM'));
SDate.add(1, 'month');
}
return allMonthList;
},
}