uni-app uni-datetime-picker组件不择任何日期直接点击确认按钮操作时报错
uni-app uni-datetime-picker组件不择任何日期直接点击确认按钮操作时报错
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | win 10 | HBuilderX |
测试过的手机
HarmonyOS 3
示例代码
<template>
<view class="page-container" >
<uni-datetime-picker ref="startDate" type="date" placeholder="开始日期" clear-icon v-model="r.startDate" />
</view>
</template>
<script setup>
import { reactive } from 'vue'
const r = reactive({
startDate: ""
})
</script>
操作步骤
- 弹出日期组件,不选择任意日期切换到下一个月;
- 不选择任何日期直接点击“确认按钮”;
预期结果
不选择任何日期直接关闭日期弹层
实际结果
非当月的所有日期会被选中,控制台报错(TypeError: Cannot read property ‘fullDate’ of undefined)
bug描述
uni-datetime-picker组件----不择任何日期直接点击确认按钮操作时uni-datetime-picke组件报错,具体异常效果见附件
组件有点小问题
uni_modules/uni-datetime-picker/components/uni-datetime-picker/calendar.vue
这个文件可以加上这段代码
if(!this.calendar){
this.calendar = this.cale.getDateObj(new Date())
}
可以可以
在使用 uni-datetime-picker
组件时,如果用户没有选择任何日期,直接点击确认按钮,可能会导致报错。这是因为 uni-datetime-picker
组件默认需要一个有效的日期值,如果用户没有选择日期,组件内部可能无法处理空值或无效值。
解决方法
-
设置默认值: 在初始化
uni-datetime-picker
组件时,可以设置一个默认的日期值,确保用户即使不选择日期,组件也有一个有效的值。<template> <uni-datetime-picker v-model="selectedDate" /> </template> <script> export default { data() { return { selectedDate: new Date().toISOString().split('T')[0] // 默认设置为今天 }; } }; </script>
-
校验用户输入: 在用户点击确认按钮时,先检查
selectedDate
是否有值,如果没有值,可以提示用户选择日期。<template> <uni-datetime-picker v-model="selectedDate" @confirm="handleConfirm" /> </template> <script> export default { data() { return { selectedDate: '' }; }, methods: { handleConfirm() { if (!this.selectedDate) { uni.showToast({ title: '请选择日期', icon: 'none' }); return; } // 处理确认操作 } } }; </script>
-
处理空值: 如果业务逻辑允许空值,可以在组件内部处理空值的情况,避免报错。
<template> <uni-datetime-picker v-model="selectedDate" @confirm="handleConfirm" /> </template> <script> export default { data() { return { selectedDate: null }; }, methods: { handleConfirm() { if (this.selectedDate === null) { // 处理空值情况 console.log('用户未选择日期'); return; } // 处理确认操作 } } }; </script>