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

v-date-picker绑定带格式化日期的v-text-field后选值清空问题

解决v-date-picker绑定格式化v-text-field后选日期清空的问题

问题:尝试将v-date-picker绑定到带日期格式化的v-text-field,使用自定义formatDate函数处理显示格式。初始加载时文本框能正常显示格式化日期,但在日期选择器中选完日期后,文本框值清空且无报错。

原代码

HTML部分

<v-menu v-model="ratingPeriodBeginMenu"
    :close-on-content-click="false"
    transition="scale-transition"
    offset-y
    max-width="290px"
    min-width="auto">
    
    <template v-slot:activator="{ props }">
        <v-text-field
            v-bind="props"
            label="Rating Period Begin Date"
            :value="formatDate(ratingPeriodBeginModel,'MM/DD/YYYY')?.toString()"
            prepend-inner-icon="mdi-calendar"
            variant="outlined"/>
    </template>
    
    <v-date-picker 
        v-model="ratingPeriodBeginModel"
        color="primary"
        no-title
        @input="ratingPeriodBeginMenu = false">
    </v-date-picker>
    
</v-menu>

格式化函数

export function formatDate(inputDate : Date | null, formatType : string) {
    if(inputDate == null) return null;
    
    if(formatType == 'MM/DD/YYYY'){
        const date = new Date(inputDate)
        return date.toLocaleDateString("en-US")
    }
}

问题原因

v-date-picker的v-model默认返回ISO 8601格式的字符串(例如"2024-05-20"),但formatDate函数参数仅接收Date | null类型。选择日期后,传入函数的是字符串而非Date对象,在TypeScript类型检查下会导致函数无法正确处理,最终返回undefined,引发文本框值清空。另外,toLocaleDateString本身已返回字符串,额外调用.toString()属于冗余操作。

修复方案

修改formatDate函数的参数类型,允许接收字符串类型的日期值,同时移除文本框中多余的.toString():

修改后的格式化函数

export function formatDate(inputDate : string | Date | null, formatType : string) {
    if(inputDate == null) return null;
    
    if(formatType == 'MM/DD/YYYY'){
        const date = new Date(inputDate)
        // 新增日期有效性检查,避免无效日期导致异常
        if(isNaN(date.getTime())) return null;
        return date.toLocaleDateString("en-US")
    }
    // 补充未匹配格式的返回逻辑,防止返回undefined
    return inputDate;
}

修改后的文本框代码

<v-text-field
    v-bind="props"
    label="Rating Period Begin Date"
    :value="formatDate(ratingPeriodBeginModel,'MM/DD/YYYY')"
    prepend-inner-icon="mdi-calendar"
    variant="outlined"/>

额外说明

  • 新增日期有效性检查,避免传入无效日期字符串时产生异常。
  • 补充未匹配格式时的返回逻辑,防止函数返回undefined导致文本框显示异常。

内容的提问来源于stack exchange,提问作者Qiuzman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:30:16