如何设置v-calendar默认月份?URL传参指定默认日期失效问题
解决v-calendar默认显示指定月份的问题
问题根源
你的代码里存在两个关键错误,导致v-calendar无法正确识别传入的日期,从而 fallback 到当前日期:
- 日期字符串格式错误:
new Date(props.occurrence + '-01T:00:00')里的时间部分多了一个冒号,正确格式应该是T00:00:00,否则Date构造函数可能解析出无效日期。 - 变量引用错误:
fromDate里直接使用了occurrence,没有加$props.前缀,导致无法正确读取props值。
修正后的代码
<v-calendar class="custom-calendar max-w-full" :masks="masks" :attributes="filteredEvents" disable-page-swipe is-expanded :from-page="props.occurrence ? new Date(`${props.occurrence}-01T00:00:00`) : new Date()" :from-date="props.occurrence ? new Date(`${props.occurrence}-01T00:00:00`) : null" v-model="selectedDate" @update:from-page="navigationHandler($event)" > <template v-slot:day-content="{ day, attributes }"> <CalendarDay :day="day" :attributes="attributes" /> </template> </v-calendar>
额外注意事项
- 初始化selectedDate:如果需要默认选中指定月份的第一天,在组件里对应初始化
selectedDate:// 选项式API data() { return { selectedDate: this.$props.occurrence ? new Date(`${this.$props.occurrence}-01`) : new Date() } } // 组合式API const selectedDate = ref(props.occurrence ? new Date(`${props.occurrence}-01`) : new Date()) - 确保props.occurrence的正确性:确认传递的
occurrence是YYYY-MM格式的字符串(比如'2022-12'),如果从URL获取,要正确解析:// 组合式API示例 const route = useRoute() const occurrence = ref(route.query.occurrence || '') - 验证navigationHandler的$event:修正后
@update:from-page的$event应该返回指定的月份日期对象,可在handler里打印确认:const navigationHandler = (event) => { console.log(event.getFullYear(), event.getMonth() + 1) // 应输出指定的年月 }
内容的提问来源于stack exchange,提问作者jones
相关产品推荐
相关产品推荐

