datetimePicker的使用
代碼片段:
-------------html----------------------------------
<van-cell-group> <van-field v-model="startTime" clearable label="開始時間" input-align="center" placeholder="請輸入開始時間" @focus="start" readonly/> <van-field v-model="endTime" clearable label="結束時間" input-align="center" placeholder="請輸入結束時間" @focus="end" readonly/> </van-cell-group> <!-- 開始時間控件 --> <van-popup v-model="showStart" position="bottom"> <van-datetime-picker v-model="currentDate" type="date" :min-date="minDate" :max-date="maxDate" @confirm="confirm" @cancel="cancel" :formatter="formatter" /> </van-popup> <!-- 結束時間控件 --> <van-popup v-model="showEnd" position="bottom"> <van-datetime-picker v-model="currentDate1" type="date" :min-date="minDate" :max-date="maxDate" @confirm="confirm1" @cancel="cancel1" :formatter="formatter" /> </van-popup>
-------------js-------------------------------------
data(){ return { minDate: null, //時間組件可選范圍 maxDate: null, date: '', currentDate: new Date(new Date().getTime()-86400000*6), //時間組件默認選中默認時間 currentDate1: new Date(), startTime: '', endTime: '', showStart: false, showEnd: false, } }, created(){ this.getMaxDate() this.restDate() }, mounted(){ }, methods:{ //初始化時間(當前一周) restDate() { this.endTime = this.formatDate(new Date()) console.log(this.endTime) //獲取前六天日期 let agoDate = new Date(new Date().getTime()-86400000*6) this.startTime = this.formatDate(agoDate) console.log(this.startTime) // this.date = `${this.startTime} - ${this.endTime}` }, // 選擇開始時間 start(e) { this.showStart = true; }, // 選擇結束時間 end(e) { this.showEnd = true; }, //最大最小時間處理 getMaxDate() { let year = new Date().getFullYear() this.minDate = new Date(year - 1, 0, 1) this.maxDate = new Date(year + 1, 11, 31) }, //日期格式 formatDate(date) { return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}` }, //確認開始日期 confirm(date) { this.showStart = false console.log(date,this.currentDate) this.startTime = this.formatDate(this.currentDate) }, //確認結束日期 confirm1(date) { this.showEnd = false console.log(date,this.currentDate1) this.endTime = this.formatDate(this.currentDate1) }, cancel(){ this.showStart = false }, cancel1(){ this.showEnd = false }, // 處理控件顯示的時間格式 formatter(type, value) { // 格式化選擇器日期 if (type === "year") { return `${value}年`; } else if (type === "month") { return `${value}月`; } else if (type === "day") { return `${value}日`; } return value; },
遇到的問題 :
1.時間組件未默認選中默認時間
解決方法:在data() 定義組件默認時間currentDate,currentDate1,組件通過v-model綁定
2.點擊輸入框會出現打字鍵盤
解決方法:在輸入框中使用readonly屬性,該屬性為只讀
3.開始時間不能大於結束時間的比較
注意:不能直接通過this.startTime和this.endTime進行比較,需要轉換成new Date()形式