微信小程式問題之picker-view日期選擇器
項目需求截圖,選擇出生日期的時候需要用到微信的picker-view日期選擇器
然後就發現官方picker-view元件有一些問題:
1、初始化日期不是目前日期
2、選擇不同月份,日期都是從1-31号(其實不同月份 天數不同)
3、項目要求所選日期不能大于目前日期(既不能選擇未來的日期)
在官方代碼上,根據項目需求做了些修改
<view class="birthBox">
<label>選擇生日</label>
<picker-view wx:if="{{years.length>0 && months.length>0 && days.length>0}}" style="width: 100%; height: 180rpx;" value="{{value}}" bindchange="bindChange">
<picker-view-column>
<view wx:for="{{years}}" wx:key="{{index}}">{{item}}年</view>
</picker-view-column>
<picker-view-column>
<view wx:for="{{months}}" wx:key="{{index}}">{{item}}月</view>
</picker-view-column>
<picker-view-column>
<view wx:for="{{days}}" wx:key="{{index}}">{{item}}日</view>
</picker-view-column>
</picker-view>
</view>
const date = new Date()
const nowYear = date.getFullYear()
const nowMonth = date.getMonth() +
const nowDay = date.getDate()
let daysInMonth = [, , , , , , , , , , , ]
// 根據年月 擷取當月的總天數
let getDays = function(year, month) {
if (month === ) {
return ((year % === ) && ((year % ) !== )) || (year % === ) ? :
} else {
return daysInMonth[month-]
}
}
// 根據年月日設定目前月有多少天 并更新年月日數組
let setDate = function (year, month, day, _th){
let daysNum = year === nowYear && month === nowMonth ? nowDay : getDays(year, month)
day = day > daysNum ? : day
let monthsNum = year === nowYear ? nowMonth :
let years = []
let months = []
let days = []
let yearIdx =
let monthIdx =
let dayIdx =
// 重新設定年份清單
for (let i = ; i <= nowYear; i++) {
years.push(i)
}
years.map((v,idx)=> {
if (v === year){
yearIdx = idx
}
})
// 重新設定月份清單
for (let i = ; i <= monthsNum; i++) {
months.push(i)
}
months.map((v, idx) => {
if (v === month) {
monthIdx = idx
}
})
// 重新設定日期清單
for (let i = ; i <= daysNum; i++) {
days.push(i)
}
days.map((v, idx) => {
if (v === day) {
dayIdx = idx
}
})
_th.setData({
years: years,//年份清單
months: months,//月份清單
days: days,//日期清單
value: [yearIdx, monthIdx, dayIdx],
year: year,
month: month,
day: day
})
}
Page({
/**
* 頁面的初始資料
*/
data: {
years: [],
months: [],
days: [],
year: nowYear,
month: nowMonth,
day: nowDay,
value: [, , ]
},
/**
* 生命周期函數--監聽頁面加載
*/
onLoad: function (options) {
setDate(this.data.year, this.data.month, this.data.day, this)
},
bindChange: function (e) {
let val = e.detail.value
setDate(this.data.years[val[]], this.data.months[val[]], this.data.days[val[]], this)
}
})