先上完成后的页面:当前年年份不显示,不然完整显示。
可以切换和自定义选择。
html:样式和图片自定义。
<view class="image-text_30">
<image @click="delMonth" :src="require('@/static/home/zuo.png')" class="icon_4"></image>
<text @click="selectMonth" lines="1" class="text-group_12">{{ currentYear == new Date().getFullYear() ? currentMonth : currentYear + '年' + currentMonth }}月</text>
<image @click="addMonth" :src="require('@/static/home/you.png')" class="icon_5"></image>
</view>
<u-datetime-picker
:show="showDateTime"
v-model="dateTime"
@close="showDateTime = false"
@cancel="showDateTime = false"
@confirm="confirmDateTime"
mode="year-month"
closeOnClickOverlay
:formatter="formatter"
></u-datetime-picker>
JavaScript:
formatter(type, value) {
if (type === 'year') {
return `${value}年`
}
if (type === 'month') {
return `${value}月`
}
return value
},
confirmDateTime(time) {
this.currentMonth = new Date(time.value).getMonth() + 1
this.currentYear = new Date(time.value).getFullYear()
this.showDateTime = false
this.calendarDate = this.currentYear + '-' + this.currentMonth
},
delMonth() {
if (this.currentMonth == 1) {
this.currentMonth = 12
this.currentYear -= 1
} else {
this.currentMonth -= 1
}
this.setTime(this.currentYear, this.currentMonth)
},
addMonth() {
if (this.currentMonth == 12) {
this.currentMonth = 1
this.currentYear += 1
} else {
this.currentMonth += 1
}
this.setTime(this.currentYear, this.currentMonth)
},
setTime(year, month) {
this.dateTime = Number(new Date(year, month - 1))
this.currentMonth = new Date(year, month - 1).getMonth() + 1
this.currentYear = new Date(year, month - 1).getFullYear()
this.calendarDate = this.currentYear + '-' + this.currentMonth
},
代码逻辑上面还是可以优化的。懒得弄了
其实没难度,但是个人简单记录下,逻辑放这里,下次需要可以再copy。