uniapp picker-view picker-view-column 选择日期一例

文档链接

https://uniapp.dcloud.io/component/picker-view.html

源码

<template>
	<view class="u-p-30">
		<u-divider>{{year}}年{{month}}月{{day}}日</u-divider>

		<picker-view :indicator-style="`height:50px;`" :value="value" @change="change" class="picker-view">
			<picker-view-column>
				<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
			</picker-view-column>
			<picker-view-column>
				<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
			</picker-view-column>
			<picker-view-column>
				<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
			</picker-view-column>
		</picker-view>

	</view>

</template>

<script>
	export default {
		data() {
			const date = new Date()
			return {
				years: []
				, currentYear: date.getFullYear()
				, year: date.getFullYear()
				, months: []
				, currentMonth: date.getMonth() + 1
				, month: date.getMonth() + 1
				, days: []
				, currentDay: date.getDate()
				, day: date.getDate()
				, value: [date.getFullYear() - 1, date.getMonth() + 1 - 1, date.getDate() - 1] // 今天
			}
		}
		, onLoad() {
			this.fillYear()
			this.fillMonths()
			this.fillDays()
		}
		, methods: {
			change(e) {
				const val = e.detail.value
				this.year = this.years[val[0]]
				this.month = this.months[val[1]]
				this.day = this.days[val[2]]
				this.fillMonths()
				this.fillDays()
			}
			, fillYear() {
				this.years = []
				for (let i = 1960; i <= this.currentYear; i++) {
					this.years.push(i)
				}
			}
			, fillMonths() {
				let max = 12
				if (this.year == this.currentYear) {
					max = this.currentMonth
				}

				this.months = []
				for (let i = 1; i <= max; i++) {
					this.months.push(i)
				}
			}
			, fillDays() {
				let max = 31
				if (this.year == this.currentYear && this.month == this.currentMonth) { // 当前月
					max = this.currentDay
				} else {
					// 根据月份显示不同的天数
					if ([1, 3, 5, 6, 8, 10, 12].includes(this.month)) { // 一三五七八十腊
						max = 31
					} else if ([4, 6, 9, 11].includes(this.month)) {
						max = 30
					} else if ([2].includes(this.month)) {
						if ((this.year % 4 == 0 && this.year % 100 != 0) || (this.year % 400 == 0)) { // 闰年
							max = 29
						} else { // 平年
							max = 28
						}
					}
				}

				this.days = []
				for (let i = 1; i <= max; i++) {
					this.days.push(i)
				}
			}
		}
	}
</script>

<style scoped>
	.picker-view {
		width: 100%;
		height: 500rpx;
		margin-top: 40rpx;
		background-color: #e0ecf8;
	}

	.picker-view .item {
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>

预览图

image

posted on 2022-09-08 10:35  小馬過河﹎  阅读(526)  评论(0)    收藏  举报

导航