最近在做一个考勤系统时,新增班次的时候需要设置打卡时段,类似如下效果:
1、封装自定义组件Time.vue
接收参数有endHour
(范围结束的小时数)、endMinute
(最后一小时结束的分钟数)等,根据具体需求变动
html
<template>
<div>
<el-cascader :options="options" v-model="selectedTime" @change="handleTimeChange" placeholder="请选择时间"></el-cascader>
</div>
</template>
<script>
export default {
props: {
endHour: Number,
endMinute: Number
},
data () {
return {
selectedTime: [],
options: []
}
},
watch: {
selectedTime () {
let minutes = this.selectedTime ? this.selectedTime[0] * 60 + this.selectedTime[1] : ''
this.$emit('input', minutes)
},
},
created() {
this.generateTimeOptions()
},
methods: {
generateTimeOptions () {
this.options = []
const startHour = 0; // 范围开始的小时数
const endHour = this.endHour; // 范围结束的小时数
const startMinutes = 1; // 范围开始的分钟数
const interval = 1; // 小时的间隔
const minutesInterval = 1; // 分钟的间隔
for (let hour = startHour; hour <= endHour; hour += interval) {
const hourValue = hour;
const hourLabel = `${hourValue}小时`;
const hourOption = {
value: hourValue,
label: hourLabel,
children: []
};
let endMinute;
if (hour === this.endHour) {
// 如果是最后一个小时,设置特定范围的分钟数
endMinute = this.endMinute; // 设置最后一个小时的结束分钟数
} else {
endMinute = 59; // 其他小时的结束分钟数为30
}
for (let minutes = hour === 0 ? startMinutes : 0; minutes <= endMinute; minutes += minutesInterval) {
const minutesValue = minutes;
const minutesLabel = `${minutesValue}分钟`;
const minutesOption = {
value: minutesValue,
label: minutesLabel
};
hourOption.children.push(minutesOption);
}
this.options.push(hourOption);
}
},
handleTimeChange (value) {
// 处理选中时间的逻辑
let timeValue = {}
timeValue.orginValue = value
timeValue.minutes = value[0] * 60 + value[1]
this.$emit('timeChange', { timeValue })
}
}
}
</script>
2、使用
引入注册组件后使用,传入动态参数,监听timeChange
方法可以拿到当前选择的时间
html
<Time :endHour="12" :endMinute="59" @timeChange="handleTimeChange"></Time>