上一篇记录了日期范围的选择;这次记录一个日期选择器的组件吧!! 场景:业务逻辑如下->当月之后置灰,12 个月前置灰;
<template>
<div>
<el-date-picker
v-model="selectedMonth"
type="month"
placeholder="选择月份"
@change="handleMonthChange"
format="yyyy-MM"
value-format="yyyy-MM"
:picker-options="pickerOptions"
:default-value="selectedMonth"
/>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue ,Emit} from 'vue-property-decorator';
@Component
export default class MonthPicker extends Vue {
@Prop({ type: String, default: '' }) readonly value!: string;
selectedMonth: string = (this.$parent.$parent as any).month||'';
get pickerOptions() {
return {
disabledDate(time: Date) {
const currentDate = new Date();
// 获取当前月份的时间戳
const currentMonthStart = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getTime();
// 获取 12 个月前的时间戳
const twelveMonthsAgo = new Date(currentDate.getFullYear(), currentDate.getMonth() - 12, 1).getTime();
// 禁用当前日期之后的日期和 12 个月前的日期之前的日期
return time.getTime() > currentMonthStart || time.getTime() < twelveMonthsAgo;
}
};
}
@Emit('date-range-changed')
handleMonthChange(value: string) {
this.selectedMonth = value;
console.log(this.selectedMonth, '子组件');
this.$emit('input', value); // 触发 input 事件以便父组件可以获取选择的月份
}
}
</script>
<style scoped>
/* 你可以在这里添加样式 */
</style>
子组件如此,父组件何为?
<el-card
class="mod-card mod-table"
shadow="never"
>
<date-selector
v-model="selectedMonth"
@date-range-changed="handleMonthInput"
/>
<!-- <p>选择的月份: {{ selectedMonth }}</p> -->
</el-card>
created() {
const currentDate = new Date();
const year = currentDate.getFullYear(); // 获取当前年份
const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 获取当前月份并格式化为两位数
const formattedDate = `${year}-${month}`; // 组合成 YYYY-MM 格式
this.month = formattedDate; // 将格式化后的结果赋值给 this.month
this.getList();
// this.initMap();
selectedMonth: string = ''; // 存储选择的月份
handleMonthInput(value: string) {
this.selectedMonth = value;
this.month = value;
this.getList();
}
}
ok,主干在此