需求:列表頁有開始日期、結束日期兩個選項,且兩者之間不能超過30天、開始日期不能晚於結束日期、結束日期不能早於開始日期的驗證
在網上查了些資料,也把想要的效果實現了,記錄一下等下次再遇到直接看筆記了
參考文章:https://www.cnblogs.com/qing619/p/9283618.html
1、HTML代碼部分
<el-form-item label="開始日期" prop="dtBegin"> <el-date-picker v-model="qryParams.dtBegin" align="right" type="date" placeholder="" format="yyyy-MM-dd" value-format="yyyyMMdd" @change="DateChange('dtBegin')" /> </el-form-item> <el-form-item label="結束日期" prop="dtEnd"> <el-date-picker v-model="qryParams.dtEnd" align="right" type="date" placeholder="" format="yyyy-MM-dd" value-format="yyyyMMdd" @change="DateChange('dtEnd')" /> </el-form-item>
因為后台需要傳遞的日期參數格式為yyyyMMdd,所以對組件設置value-format=“yyyyMMdd”屬性
2、獲取當前日期
// 顯示當前日期的明天日期值(yyyy-MM-dd格式) getNowDate() { const _date = new Date().getTime() + 24 * 60 * 60 * 1000 const d1 = new Date(_date) // console.log(d1, '當前日期') const year = d1.getFullYear() let month = d1.getMonth() + 1 let date = d1.getDate() if (month < 10) { month = '0' + month } if (date < 10) { date = '0' + date } return year + month + date // return d1 },
這里 const _date = new Date().getTime() + 24 * 60 * 60 * 1000 是因為我需要獲取明天的日期,獲取哪天的根據需要加減即可:+ n * 24 * 60 * 60 * 1000或 - n * 24 * 60 * 60 * 1000(n代表往前或往后的天數),比如我想要當前日期后天的時間戳毫秒數,
const _date = new Date().getTime() + 2 * 24 * 60 * 60 * 1000,
2、給日期組件綁定change事件及驗證
// 開始、截止日期change事件 DateChange(type) { const days = this.dateDiff(this.qryParams.dtBegin, this.qryParams.dtEnd, type) if (days > 30) { this.$alert('查詢日期不能超過30天', '提示', { confirmButtonText: '確定', confirmButtonClass: 'ticket-comfirm-btn', callback: () => {} }) if (type === 'dtBegin') { this.qryParams.dtBegin = '' } else { this.qryParams.dtEnd = '' } } }, // 開始/結束日期間隔不超過30天、開始日期晚於結束日期、結束日期早於開始日期驗證 dateDiff(startDt, endDt, type) { // 20200303轉成2020-03-03格式 const startDate = stringConcat(startDt) const endDate = stringConcat(endDt) // 2020-03-03轉new Data()對象 const startTimes = new Date(startDate) const endTimes = new Date(endDate) // 獲取開始、截止時間的毫秒數 const startTimesNum = startTimes.getTime(startTimes) const endTimesNum = endTimes.getTime(endTimes) if (endTimesNum - startTimesNum < 0 && type === 'dtBegin') { this.$alert('開始日期不能晚於結束日期', '提示', { confirmButtonText: '確定', confirmButtonClass: 'ticket-comfirm-btn', callback: () => {} }) this.qryParams.dtBegin = '' return } else if (endTimesNum - startTimesNum < 0 && type === 'dtEnd') { this.$alert('結束日期不能早於開始日期', '提示', { confirmButtonText: '確定', confirmButtonClass: 'ticket-comfirm-btn', callback: () => {} }) this.qryParams.dtEnd = '' return } const days = parseInt((endTimesNum - startTimesNum) / 24 / 60 / 60 / 1000) return days }
可能總結得不好,不過我就是給自己做個筆記,下次遇到直接拿過來就用了,大概就這樣吧
