实现当月和接下来7天的标签页
在这一步中,你将学习如何实现允许用户在当月数据和接下来7天的数据之间切换的标签页。
在 index.html
文件中,在Vue实例的 data
部分,添加以下属性:
data: {
type: 1, // 接下来7天和当月的数据状态
nowMonth: new Date().getMonth(),
},
在 id="currentMonth"
的 <div>
中,根据 monthNumber
和 nowMonth
属性添加条件渲染。这将只显示当月的标签页。
<div id="currentMonth" v-if="monthNumber===nowMonth">
<div class="title">
<h3>{{typeTitle}}</h3>
<div class="type" @click="clickType($event)">
<span id="seven" :class="{'active':!type}">接下来7天</span>
<span id="current" :class="{'active':type}">当月</span>
</div>
</div>
</div>
在Vue实例的 methods
部分,添加 clickType()
方法,该方法根据点击的标签更新 type
、typeTitle
、yData
和 xData
属性,然后调用 initChart()
方法重新渲染图表。
clickType(e) {
switch (e.target.id) {
case "seven":
this.type = 0;
this.typeTitle = "接下来7天";
[this.xData, this.yData] = this.getSevenData();
break;
case "current":
this.type = 1;
this.typeTitle = "当月";
this.yData = this.data[this.monthNumber][this.monthName];
this.xData = [...this.yData.map((e, i) => i + 1)];
break;
}
this.initChart();
},
添加 getSevenData()
方法,该方法计算接下来7天的x轴标签和y轴数据。
getSevenData() {
let newXdata = [],
newYdata = [];
for (let i = 0; i < 7; i++) {
let now = new Date();
let time = now.getTime() + 1000 * 60 * 60 * 24 * i;
now.setTime(time);
newXdata.push(`${now.getMonth() + 1}/${now.getDate()}`);
if (this.monthNumber === now.getMonth()) {
newYdata.push(this.yData[now.getDate() - 1]);
} else {
let nextMonth = this.data[now.getMonth()];
for (const key in nextMonth) {
newYdata.push(nextMonth[key][now.getDate() - 1]);
}
}
}
return [newXdata, newYdata];
},
此方法计算接下来7天的x轴标签和y轴数据,同时考虑到月份之间的过渡。
保存文件并重新加载页面以查看更新后的图表。下图显示了在“当月”和“接下来7天”之间切换的效果(通过时间函数获取,这里假设是四月):
月份切换效果如下: