工作中遇到一个需求效果如下:
当我们点击选择年度的时候,选择器面板切换为年度范围的效果,同理,当我们点击选择年份的时候,选择器面板切换为年份选择的效果
- 实现方式就是要借助vue的动态组件封装
子组件
<template>
<Component :is="comp[currentComp]" v-bind="config" :open="isOpen" format="YYYY" v-on="listeners">
<template slot="renderExtraFooter">
<a-button type="link" @click="toggleShowYear">{{ showYear ? '选择年度' : '选择年份' }}</a-button>
</template>
</Component>
</template>
<script setup>
import { ref } from 'vue';
import { DatePicker } from 'ant-design-vue';
import moment from 'moment';
const showYear = ref(true);
const isOpen = ref(false);
const props = defineProps(['value']);
const emit = defineEmits(['input']);
const comp = {
date: DatePicker,
range: DatePicker.RangePicker,
};
const config = ref({
mode: 'year',
placeholder: '填报年度',
value: props.value,
});
const currentComp = ref('date');
const handleOpenYear = (open) => {
isOpen.value = open;
};
const handleChangeYear = (value) => {
if (Array.isArray(value)) {
emit('input', [moment(value[0]).format('YYYY'), moment(value[1]).format('YYYY')]);
} else {
emit('input', moment(value).format('YYYY'));
}
config.value.value = value;
isOpen.value = false;
};
const clearYear = () => {
config.value.value = null;
emit('input', null);
};
const toggleShowYear = () => {
showYear.value = !showYear.value;
if (showYear.value) {
currentComp.value = 'date';
config.value = {
mode: 'year',
placeholder: '请选择年份',
value: null,
};
} else {
currentComp.value = 'range';
config.value = {
mode: ['year', 'year'],
placeholder: ['开始', '结束'],
value: [],
};
}
};
const listeners = ref({
openChange: handleOpenYear,
panelChange: handleChangeYear,
change: clearYear,
});
</script>
父组件
<YearSwitch v-model="formInline.yearVal" />