日期时间选择(设置禁用状态)
目录
1.element文档需要
2.禁用所有过去的时间
3.设置指定日期的禁用时间
<template><div class="block"><span class="demonstration">起始日期时刻为 12:00:00</span><el-date-pickerv-model="value1"type="datetimerange"start-placeholder="开始日期"end-placeholder="结束日期":default-time="['12:00:00']"></el-date-picker></div>
</template><script>export default {data() {return {value1: ''};}};
</script>
1.element文档需要
Element - The world's most popular Vue UI framework
picker-options
<template><div class="block"><span class="demonstration">起始日期时刻为 12:00:00</span><el-date-pickerv-model="value1"type="datetimerange"start-placeholder="开始日期"end-placeholder="结束日期":picker-options="pickerOptions"></el-date-picker></div>
</template><script>export default {data() {return {value1: ''};},};
</script>
:picker-options="pickerOptions"
2.禁用所有过去的时间
computed:{pickerOptions(){return {disabledDate:this.disabledDate()}}},
methods:{disabledDate(time){console.log(time)return time<Date.now()}
}
disabledDate
是一个函数,用于判断某个日期是否应该被禁用。这个函数会在日期选择器中每个日期渲染时被调用,传入当前日期的 timestamp(时间戳),返回一个布尔值,表示该日期是否被禁用。
Date.now() 返回当前时间的时间戳(即从1970年1月1日00:00:00 UTC开始经过的毫秒数)
time<Date.now() 表示如果传入的 time (选中的日期时间戳)小于当前时间的时间戳,则会返回 true,表示该日期应该被禁用
换句话说,这个逻辑会禁用所有过去的时间
3.设置指定日期的禁用时间
假如现在有个指定日期选择器
<template><div class="block"><span class="demonstration">默认</span><el-date-pickerv-model="time"type="date"value-format="timestamp"placeholder="选择日期"></el-date-picker></div>
</template><script>export default {data() {return {time: '',};}};
</script>
此时data中的time就是需要的指定日期
value-format="timestamp"返回时间戳
computed:{pickerOptions(){return {disabledDate:this.disabledDate()}}},
disabledDate(time) {let allowedDate = new Date(this.time);console.log('allowedDate',allowedDate); let startOfDay = new Date(allowedDate.getFullYear(), allowedDate.getMonth(), allowedDate.getDate());let endOfDay = new Date(allowedDate.getFullYear(), allowedDate.getMonth(), allowedDate.getDate() + 1);return time.getTime() < startOfDay.getTime() || time.getTime() >= endOfDay.getTime();},
打印结果;
完整代码:
<template><div class="block"><el-date-pickerv-model="time"type="date"value-format="timestamp"placeholder="选择日期"></el-date-picker>//设置禁用时间<el-date-pickerv-model="value1"type="datetimerange"start-placeholder="开始日期"end-placeholder="结束日期":picker-options="pickerOptions"></el-date-picker></div>
</template><script>export default {computed:{pickerOptions(){return {disabledDate:this.disabledDate()}}},data() {return {value1: '',time:'',};},methods:{disabledDate(time) {let allowedDate = new Date(this.time); let startOfDay = new Date(allowedDate.getFullYear(), allowedDate.getMonth(), allowedDate.getDate());let endOfDay = new Date(allowedDate.getFullYear(), allowedDate.getMonth(), allowedDate.getDate() + 1);return time.getTime() < startOfDay.getTime() || time.getTime() >= endOfDay.getTime();},}};
</script>
展示