封装日期时间限制控件,文件放在interface/index.ts文件夹里;
// 封装的日期禁用控件。interface/index.ts
import {toRefs} 'vue';
export interface ClassifyDate {
startDate:any;
}
/**
@description: 判断今年是闰年还是平年。闰年366天 平年365天
@return {*}
**/
const getDay = () => {
const years = new Date().getFullYear();
if ((years % 4 === 0 && years % 100 === 0) || years % 400 === 0) {
return 366;
} else {
return 365;
}
};
/**
@description: 日期控件的封装
@param {number} day // 日期控件限制时间跨度,非必穿,默认一年
@return {*}
**/
export const useDatePicker = (day:number = getDay()) => {
const state = reactive<ClassifyDate>({
startDate: null, // 日期选择的开始时间
});
//获取点击开始的时间
const calendarChange = (dates:any) => {
const hasSelectDate = dates !== null && dates.length > 0;
state.startDate = hasSelectDate ? dates[0].getTime() : null;
};
// 当日期控件下拉列表出现/消失时触发 - 解除日期控件打开解除禁用时间限制
const visibleChange = (visibility: boolean) => {
if (visibility) {
state.startDate = null;
}
};
// 嘉奖日期 开始日期和结束日期的日期间隔不能超过一年
const disabledDate = (time:Record<string,any>):boolean => {
if(state.startDate){
return time.getTime() < state.startDate || time.getTime() > state.startDate + day * 8.64e7; // 8.64e7相当于一天的时间戳
}else{
return false;
}
};
return {
...toRefs(state),
calendarChange,
visibleChange,
disabledDate
};
};
组件引用封装日期控件时间限制事件
// 引用日期组件
<el-date-picker v-model="date"
type="daterange"
start-placeholder="开始日期"
end-placeholder="结束日期"
value-format="YYYY-MM-DD"
:default-value="defaultValue"
@clearble="false"
@calendar-change="calendarChange"
:disabled-date="disabledDate"
@visible-change="visibleChange">
</el-date-picker>
<script lang="ts" setup>
import {ref} from 'vue';
import {calendarChange,disabledDate,visibleChange} from './interface/index';
const date = ref<any>(/**初始值**/);
</script>
该博客介绍了如何在Vue3项目中结合Element Plus和TypeScript来封装一个带有时间范围限制的日期选择组件。内容包括组件的封装过程和在interface/index.ts文件夹中的组织方式,以及如何处理时间限制的事件。
3198

被折叠的 条评论
为什么被折叠?



