You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置v-calendar默认月份?URL传参指定默认日期失效问题

解决v-calendar默认显示指定月份的问题

问题根源

你的代码里存在两个关键错误,导致v-calendar无法正确识别传入的日期,从而 fallback 到当前日期:

  1. 日期字符串格式错误:new Date(props.occurrence + '-01T:00:00') 里的时间部分多了一个冒号,正确格式应该是 T00:00:00,否则Date构造函数可能解析出无效日期。
  2. 变量引用错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 01:10:28