前段时间搞了个公众号,我用的Vant-ui,Vant官方网站,毕竟是有赞团队开发的,项目需求有个地方用到日历,这个组件:
<van-datetime-picker
v-model="currentDate"
:type="dateType"
@cancel="showPickerTime = false"
@confirm="onConfirm"
:formatter="formatter"
/>
里面主要说明两个属性:type和formatter,为什么要单独说,因为项目需要,有日、月、年三个选项,而官方文档上type的说明:

有日,有月,没有年。。。
于是二话不说就开始研究啊,咦,有个formatter属性很有意思,大家想必都知道,在各种组件上面,这个属性就代表可以修改格式啊,官方操作看一波:

formatter(type, value) {
if (type === 'year') {
return `${value}年`;
} else if (type === 'month') {
return `${value}月`;
}
return value;
}
哈哈,这一看就明白,在用户选择日这种日期类型,type=date
在用户选择月这种日期类型,type=year-month
在用户选择年这种日期类型,type=year-month
月和年是被迫一样的,因为只有这个,然后是重点:
formatter (type, value) {
if (this.dateActive == 0) { // 日
if (type === 'year') {
return `${value}`
} else if (type === 'month') {
return `${value}`
}
return value;
} else if (this.dateActive == 1) { // 月
if (type === 'year') {
return `${value}`
} else if (type === 'month') {
return `${value}`
}
return value;
} else if (this.dateActive == 2) { // 年
if (type === 'year') {
return `${value}`
} else if (type === 'month') {
return `` // 重点就是这里,把‘月’给返回空字符串
}
return value;
}
},
到这里,日历就可以按照日、月、年展示了:
日:

月:

年:

emmmmm,看见问题了吗,年后面的这片空白。
做人,最重要的是开心嘛,der

本文详细介绍了如何使用Vant-ui的DatetimePicker组件实现日、月、年的选择功能,通过formatter属性自定义显示格式,解决官方文档中未直接提供年份选择的问题。
1676

被折叠的 条评论
为什么被折叠?



