简述:这篇博客主要内容是mintui的datetimepicker插件的扩展使用。基础的引入和使用都可以在官方文档中查到,这里就不再赘述,我的项目中需要有一个前一天、后一天的快捷入口,需要与datepicker插件联动起来,先讲一下大致实现:
需求:这么一个样式,右侧为前一天后一天的切换,同时需要左侧时间联动变化。
贴代码:template:
<div class="fl" @click="openDatePicker()">{{pickerValue | toTime}}</div>
<div class="fr">
<a href="javascript:;" class="dateBtn" :class="someday>-1?'disabledBtn':''" @click="subDate()"><i class="moreIcon toLeft"></i></a>
<a href="javascript:;" class="dateBtn" :class="someday>=-1?'disabledBtn':''" @click="addDate()"><i class="moreIcon toRight"></i></a>
</div>
<mt-datetime-picker
ref="picker"
type="date"
v-model="pickerValue"
year-format="{value}年"
month-format="{value}月"
date-format="{value}日"
@confirm="handleConfirm">
</mt-datetime-picker>
script 的filter就不贴了,就Date类型转字符串
script 的 methods:
getData(subtract) { // 根据日期(yyyy-mm-dd)获取数据,参数为比今天早的天数
if (!subtract) {
subtract = -1
}
let today = new Date();
today.setDate(today.getDate() + subtract); // Date对象的方法
let time = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
// 根据日期请求数据
},
openDatePicker() { // 打开时间选择器
this.$refs.picker.open()
},
subDate() { // 前一天
if (this.someday > -1) {
return
}
this.someday--
let now = new Date();
now.setDate(now.getDate() + this.someday)
this.pickerValue = now
this.getData(this.someday)
},
addDate() { // 后一天
if (this.someday >= -1) {
return
}
this.someday++
let now = new Date();
now.setDate(now.getDate() + this.someday)
this.pickerValue = now
this.getData(this.someday)
},
handleConfirm() { // 选定时间
let now = new Date()
now.setDate(now.getDate()-1)
if (now.getTime() - this.pickerValue.getTime() < 0) {
// 日期插件关联快捷加减日期
this.pickerValue = now
this.someday = -1
} else{
this.someday = - 1 - Math.floor((now.getTime() - this.pickerValue.getTime())/(1000*24*3600))
}
// 请求
},
以上是大白话类型的思路了,没有经过优化,比较粗糙。这个功能有一个bug就是在有31日的月份点击下一天的时候,会导致在组件渲染弹出框的时候重新给pickerValue赋值,月份没有变化,导致显示如 2019-05-31时点击后一天为2019-05-01,再后一天由于someday正常,后面的日期也会正常。
问题的解决办法:监听pickerValue
pickerValue() {
let now = new Date();
now.setDate(now.getDate() + this.someday)
if (this.pickerValue.getMonth()!==now.getMonth()){
this.pickerValue = now
}
}
可以解决。
做个笔记,如果能帮到看到文章的你,那就太好了