首先創(chuàng)建wxml結構
<picker-view class="pickerView" indicator-style="height: 40px;" :value="value" @change="bindDateChangeStart" @click.stop="">
<picker-view-column class="pickerColumn">
<div class="pickerItem" v-for="(item,key) in years" :key='key'>{{item}}年</div>
</picker-view-column>
<picker-view-column class="pickerColumn">
<div class="pickerItem" v-for="(item,key) in months" :key='key'>{{item}}月</div>
</picker-view-column>
<picker-view-column class="pickerColumn">
<div class="pickerItem" v-for="(item,key) in days" :key='key'>{{item}}日</div>
</picker-view-column>
</picker-view>
然后我們定義數(shù)據(jù)
data(){
return {
years: 0,
months: 0,
days: 0,
value: [8, 1, 1],//默認滾動的索引值
}
}
然后我們初始化數(shù)據(jù)initDatas
initDatas () {
const date = new Date()
const nowYear = date.getFullYear()
const nowMonth = date.getMonth() + 1
const nowDay = date.getDate()
this.year = nowYear
this.month = nowMonth
this.day = nowDay
// 循環(huán)前先清空數(shù)組
this.years = []
this.months = []
for (let i = nowYear-30; i <= nowYear; i++) {
this.years.push(i)
}
// 設置月份列表
for (let i = 1; i <= 12; i++) {
this.months.push(i)
}
// 初始化當前年月
if(this.birthday && this.birthday.indexOf('-')!=-1){
var birthday_obj = this.birthday.split('-');
this.getMonth(parseInt(birthday_obj[0]), parseInt(birthday_obj[1]), parseInt(birthday_obj[2]))
}else{
this.getMonth(nowYear, nowMonth, nowDay)
}
},
getMonth (year, month, day) {
let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
let dayNum = 0
// 通過年和月獲取這個月份下有多少天
if (month === 2) { // 閏年
dayNum = ((year % 4 === 0) && ((year % 100) !== 0)) || (year % 400 === 0) ? 29 : 28
} else {
dayNum = daysInMonth[month - 1]
}
this.days = []
for (let i = 1; i <= dayNum; i++) {
this.days.push(i)
}
// 初始 選中年月日對應下標
let yearIdx = 0
let monthIdx = 0
let dayIdx = 0
// 獲取滾動后 年月日對應的下標
this.years.map((v, idx) => {
if (v === year) {
yearIdx = idx
}
})
this.months.map((v, idx) => {
if (v === month) {
monthIdx = idx
}
})
this.days.map((v, idx) => {
if (v === day) {
dayIdx = idx
}
})
// 重置滾動后 年月日 的下標
this.value = [yearIdx, monthIdx, dayIdx]
// 賦值年月日
this.year = this.years[yearIdx]
this.month = this.months[monthIdx]>9?this.months[monthIdx]:'0'+this.months[monthIdx]
this.day = this.days[dayIdx]>9?this.days[dayIdx]:'0'+this.days[dayIdx]
},
當用戶滑動的時候叶堆,觸發(fā)bindDateChangeStart事件
bindDateChangeStart (e) {
// valIndex 是獲取到的年月日在各自集合中的下標
const valIndex = e.mp.detail.value
// console.log(JSON.stringify(e.mp.detail.value))
let year = this.years[valIndex[0]]
let month = this.months[valIndex[1]]
let day = this.days[valIndex[2]]
// 滾動時再動態(tài) 通過年和月獲取 這個月下對應有多少天
this.getMonth(year, month, day)
},