在Vue3+TS中实现此功能,并遵循不使用this和$的要求,我们可以使用Composition API的reactive和ref函数来创建响应式数据和引用。以下是一个示例代码:
vue Copy code
<template>
<div>
<select v-model="queryMode">
<option value="day">按天</option>
<option value="week">按周</option>
<option value="month">按月</option>
</select>
<input type="date" :value="startDate" :min="minStart" :max="maxStart" @input="updateStartDate" />
<input type="date" :value="endDate" :min="minEnd" :max="maxEnd" @input="updateEndDate" />
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, watch, Ref } from 'vue';
export default defineComponent({
setup() {
const queryMode: Ref<string> = ref('day');
const startDate: Ref<string> = ref('');
const endDate: Ref<string> = ref('');
const updateStartDate = (event: Event) => {
startDate.value = (event.target as HTMLInputElement).value;
};
const updateEndDate = (event: Event) => {
endDate.value = (event.target as HTMLInputElement).value;
};
const minStart = computed(() => {
if (queryMode.value === 'week') {
const currentDate = new Date();
const currentDay = currentDate.getDay();
const firstDayOfWeek = new Date(currentDate.setDate(currentDate.getDate() - currentDay));
return firstDayOfWeek.toISOString().split('T')[0];
}
if (queryMode.value === 'month') {
const currentDate = new Date();
const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
return firstDayOfMonth.toISOString().split('T')[0];
}
return '';
});
const maxStart = computed(() => {
if (queryMode.value === 'week') {
return new Date().toISOString().split('T')[0];
}
if (queryMode.value === 'month') {
return new Date().toISOString().split('T')[0];
}
return '';
});
const minEnd = computed(() => {
return startDate.value;
});
const maxEnd = computed(() => {
return new Date().toISOString().split('T')[0];
});
watch(queryMode, () => {
startDate.value = '';
endDate.value = '';
});
watch(startDate, (newStartDate) => {
if (queryMode.value === 'day' && endDate.value && newStartDate > endDate.value) {
endDate.value = '';
}
});
watch(endDate, (newEndDate) => {
if (queryMode.value === 'day' && startDate.value && newEndDate < startDate.value) {
startDate.value = '';
}
});
return {
queryMode,
startDate,
endDate,
minStart,
maxStart,
minEnd,
maxEnd,
updateStartDate,
updateEndDate
};
}
});
</script>
在这个示例代码中,我们使用了ref函数和reactive函数来创建响应式的引用和状态对象。使用computed函数来计算minStart、maxStart、minEnd和maxEnd的计算属性,它们的值会根据queryMode和startDate的变化而自动更新。
通过使用@input事件监听输入框的输入,我们将输入框的值绑定到引用变量中。然后通过计算属性分别提供给日期选择器的min和max属性。根据选择的查询方式,限制了开始和结束日期的可选范围。
通过watch监听queryMode、startDate和endDate的变化,我们可以实时地在值发生变化时更新其他相关的值。
这个示例代码符合Vue3的Composition API规范,并遵循了不使用this和$的要求。您可以根据您的具体需求和样式进行进一步的修改。