描述
主要功能点:监听日期的变化,致默认选择日期以及禁用日期的范围变化,示例放在Vue3中
需求描述:
月份默认当前月,下月为禁用状态
日期默认当前月1号到今天,今日之后及非当前月的日期为禁用状态
当月份选择其他月份时,日期默认值为这个月的1号到月末,非所选月的日期禁选
功能展示
当前月:
所选非当前月:
代码
<el-date-picker
v-model="month"
type="month"
placeholder="请选择月份"
value-format="YYYY-MM"
:clearable="false"
:editable="false"
:disabled-date="getDisabledMonth"
/>
<el-date-picker
v-model="dateTime"
type="daterange"
range-separator="-"
start-placeholder="起始时间"
end-placeholder="结束时间"
value-format="YYYY-MM-DD"
:clearable="false"
:editable="false"
:disabled-date="getDisabledDate"
/>
<script setup>
import { standardTime } from '@/utils/common'
const month = ref(standardTime(new Date(), 'yyyy-MM'))
// 禁选月份/日期
const getDisabledMonth = (time) => {
return time.getTime() > Date.now()
}
const getDisabledDate = (time) => {
return (
time.getTime() > Date.now() ||
time.getTime() < new Date(getDateRange(month.value)[0].replace(/-/g, '/')).getTime() ||
time.getTime() > new Date(getDateRange(month.value)[1].replace(/-/g, '/')).getTime()
)
}
// 获取默认 起始时间-结束时间(当月1号-当天,不是当月1号到月末)
// month:yyyy-MM
function getDateRange(month) {
const date1 = new Date(month) //将传入的时间字符串转换成时间对象
const date2 = new Date() //当前时间
const dateRange = []
// console.log('月份---', standardTime(date1, 'yyyy-MM'), '|', standardTime(date2, 'yyyy-MM'))
// console.log('1号', standardTime(date1, 'yyyy-MM') + '-01')
// console.log('最后一日', standardTime(new Date(date1.getFullYear(), date1.getMonth() + 1, 0)))
// 所选月份1号
dateRange.push(standardTime(date1, 'yyyy-MM') + '-01')
if (standardTime(date1, 'yyyy-MM') === standardTime(date2, 'yyyy-MM')) {
// 如果当月就当天
dateRange.push(standardTime(new Date(), 'yyyy-MM-dd'))
} else {
// 不是当月就最后一天
dateRange.push(standardTime(new Date(date1.getFullYear(), date1.getMonth() + 1, 0)))
}
return dateRange
}
watch(
month,
() => {
dateTime.value = getDateRange(month.value)
},
{ immediate: true }
)
</script>
自定义日期格式化方法
自己写的日期格式化方法,其中flag参数可传‘start’、'end'或不传,已方便得到需要的时分秒格式
common.js
/**
* 中国标准时间转年月日 Thu Mar 12 2020 00:00:00 GMT+0800 (中国标准时间) yyyy-MM-dd
* flag:start:00:00:00|end:23:59:59|默认时间
*/
export function standardTime(time, type = 'yyyy-MM-dd', flag) {
if (!time) {
return
}
const d = new Date(time)
const count = function (num) {
// 补零
if (num >= 10) {
return num
}
return `0${num}`
}
let datetime = ''
if (type === 'yyyy-MM-dd') {
datetime = d.getFullYear() + '-' + count(d.getMonth() + 1) + '-' + count(d.getDate())
} else if (type === 'yyyy-MM-dd HH:mm:ss') {
if (flag === 'start') {
datetime = d.getFullYear() + '-' + count(d.getMonth() + 1) + '-' + count(d.getDate()) + ' 00:00:00'
} else if (flag === 'end') {
datetime = d.getFullYear() + '-' + count(d.getMonth() + 1) + '-' + count(d.getDate()) + ' 23:59:59'
} else {
// 日期自身带有时分秒
datetime =
d.getFullYear() +
'-' +
count(d.getMonth() + 1) +
'-' +
count(d.getDate()) +
' ' +
count(d.getHours()) +
':' +
count(d.getMinutes()) +
':' +
count(d.getSeconds())
}
} else if (type === 'yyyy-MM') {
datetime = d.getFullYear() + '-' + count(d.getMonth() + 1)
}
return datetime || ''
}