【效果图】
【HTML】
<picker-view v-if="visible" :indicator-style="indicatorStyle" :value="value"
@change="bindChange">
<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>
【Script】
1.生成当前年月日
2.生成总的年月日数组
data() {
const date = new Date()
const years = []
const year = date.getFullYear()
const months = []
const month = date.getMonth() + 1
const days = []
const day = date.getDate()
const zv = {
year: [],
month: [],
day: [],
} //总数组
for (let i = 1940; i <= date.getFullYear(); i++) {
years.push(i)
zv.year.push(i)
}
for (let i = 1; i <= 12; i++) {
months.push(i)
zv.month.push(i)
}
for (let i = 1; i <= 31; i++) {
days.push(i)
zv.day.push(i)
}
return {
years,
year,
months,
month,
days,
day,
zv,
value: [9999, month - 1, day - 1],
visible: true,
indicatorStyle: 'height: 50px;'
};
},
//日期设置
bindChange(e) {
let that = this;
console.log(e.detail.value)
const val = e.detail.value;
let d = new Date()
let y = d.getFullYear();
let m = d.getMonth() + 1; //月
let dayx = d.getDate();
// 设置当前年份的月份
if (that.years[val[0]] == y) {
that.months = that.months.slice(0, m);
} else {
that.months = that.zv.month;
}
that.days = that.zv.day;
if (that.months[val[1]] == m && that.years[val[0]] == y) {
// 设置当前月份的日期
that.days = that.days.slice(0, dayx)
} else if ([4, 6, 9, 11].includes(that.months[val[1]])) {
// 设置大小月
that.months = that.zv.month;
that.days = that.days.slice(0, 30)
} else if (that.months[val[1]] == 2) {
const year = that.years[val[0]];
//设置二月
if ((year % 4 == 0 && !(year % 100 == 0)) || year % 400 == 0) {
// 闰年
that.days = that.days.slice(0, 29)
} else {
// 平年
that.days = that.days.slice(0, 28)
}
}
that.year = that.years[val[0]]
that.month = that.months[val[1]]
that.day = that.days[val[2]]
},