自己寫的 uni-app 的日期選擇器

HTML部分 

<view class="uni-list-cell">
	<view class="uni-list-cell-left">選擇時間</view>
	<view class="uni-list-cell-db">
		<picker mode="selector" :range="currDate" @change="onDateChange">
			<view class="uni-input" style="text-align: right;">{{time}}</view>
		</picker>
	</view>
</view>

JS部分

export default {
    data () {
        const date = new Date()
		const years = []
		const year = date.getFullYear()
		const months = []
		const month = date.getMonth() + 1
		for (let i = 2018; i <= date.getFullYear(); i++) {   //這裏是以2018開始,也可以換成其他任意年份
			years.push(i);
		}
		for (let i = 1; i <= 12; i++) {
			months.push(i)
		}
        return {
            years,
			year,
			months,
			month,
			currDate: [],
			time: ''
        }
    },
    onload () {
        this.time = this.year + "-" + this.month;
		for ( let i=0;i<this.years.length;i++) {
			if (this.year == this.years[i]) {   // 判斷當前循環到的年份是否是本年,是的話則月份不可以超過當前月份
				for (let j=0; j<this.month; j++) {
					const date = this.years[i] + "-" + this.months[j]
					this.currDate.push(date)
				}
			} else {
				for (let j=0; j<this.months.length;j++) {  //其他年份
					const date = this.years[i] + "-" + this.months[j]
					this.currDate.push(date)
				}
			}
		}
		this.currDate.reverse();   //將時間倒序排列
    },
    methods: {
        onDateChange: function (e) {
			const val = e.detail.value
			this.time = this.currDate[val];
            // 時間選擇完成了,這之後就可以做一些其他的事情啦
		},
    }
}

附上一張Android的效果圖

嗯……大概就是這樣,有問題的話請大家幫忙指出~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章