前端vue,今天,14天,30天,时间切换
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0e6ebab1128a1287d51b3402514073c9.png)
前端样式
<div>
<span style="margin-left: 10px;font-size: medium" class="options">时间:
<sapn style="margin-left: 10px" class="option active" @click="changeDays('1')" id="1">今天</sapn>
<sapn style="margin-left: 10px" class="option" @click="changeDays('2')" id="2">14天</sapn>
<sapn style="margin-left: 10px" class="option" @click="changeDays('3')" id="3">30天</sapn>
</span>
<el-date-picker
style="width: auto;margin-left: 10px;margin-top: 5px"
v-model="dateSelection"
size="mini"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
value-format="yyyy-MM-dd">
</el-date-picker>
</div>
定义变量
return {
timeQuery: {
startTime: '',
endTime: '',
},
nowTime: '',
currentTime: '',
fourteenDays: '',
thirtyDays: '',
dateSelection: [],
}
Js方法
methods: {
async changeDays(days) {
for (let i = 1; i <= 3; i++) {
document.getElementById(i.toString()).classList.remove('active');
}
if (days != undefined ){
document.getElementById(days).classList.add('active');
this.dateSelection = null;
this.timeQuery.endTime = this.currentTime;
if (days == 2) {
this.timeQuery.startTime = this.fourteenDays;
}else if (days == 3) {
this.timeQuery.startTime = this.thirtyDays;
}else {
this.timeQuery.startTime = this.currentTime;
}
}
let params = this.urlEncodeObject(this.timeQuery);
const {code, data} = await timeQueryList(params);
if (code != "200") return;
},
formatDate(date) {
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, "0");
let day = date.getDate().toString().padStart(2, "0");
let hours = date.getHours().toString().padStart(2, "0");
let minutes = date.getMinutes().toString().padStart(2, "0");
let seconds = date.getSeconds().toString().padStart(2, "0");
return year + "-" + month + "-" + day + "" +hours + ":" + minutes + ":" +seconds;
},
getNowYMD() {
let date = new Date();
let day = date.getDate();
this.formatDate(date);
this.currentTime = formatDate(date);
let fourteenDaysAgo = new Date(date);
this.fourteenDays = formatDate(fourteenDaysAgo.setDate(day- 14));
let thirtyDaysAgo = new Date(date);
this.thirtyDays = formatDate( thirtyDaysAgo.setDate(day- 30));
},
},
mounted() {
this.changeDays(1);
},
watch:{
dateSelection(){
if (this.dateSelection !== null) {
this.timeQuery.startTime = this.formatDate(this.dateSelection[0]);
this.timeQuery.endTime = this.formatDate(this.dateSelection[1]);
this.changeDays();
}else{
this.changeDays(1);
}
}
}