使用uni中的picker-view实现一个可以使用的滚动I日期选择期,并实现月份变化日期也变化
时间: 2024-02-06 12:12:50 浏览: 103
好的,以下是示例代码:
```html
<template>
<view>
<picker-view
:value="dateValue"
@change="onDateChange"
style="width: 100%; height: 200px;"
>
<picker-view-column>
<view v-for="(year, index) in years" :key="index">{{ year }}</view>
</picker-view-column>
<picker-view-column>
<view v-for="(month, index) in months" :key="index">{{ month }}</view>
</picker-view-column>
<picker-view-column>
<view v-for="(day, index) in days" :key="index">{{ day }}</view>
</picker-view-column>
</picker-view>
</view>
</template>
<script>
export default {
data() {
const now = new Date();
const years = [];
const months = [];
const days = [];
for (let i = now.getFullYear() - 10; i <= now.getFullYear() + 10; i++) {
years.push(i);
}
for (let i = 1; i <= 12; i++) {
months.push(i);
}
const maxDays = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
for (let i = 1; i <= maxDays; i++) {
days.push(i);
}
return {
years,
months,
days,
dateValue: [
years.indexOf(now.getFullYear()),
months.indexOf(now.getMonth() + 1),
days.indexOf(now.getDate()),
],
};
},
methods: {
onDateChange(e) {
const [yearIndex, monthIndex] = e.detail.value;
const year = this.years[yearIndex];
const month = this.months[monthIndex];
const maxDays = new Date(year, month, 0).getDate();
const days = [];
for (let i = 1; i <= maxDays; i++) {
days.push(i);
}
const dateValue = [...e.detail.value];
const dayIndex = Math.min(dateValue[2], days.length - 1);
dateValue[2] = dayIndex;
this.days = days;
this.dateValue = dateValue;
},
},
};
</script>
```
这里使用了`picker-view`组件,并通过`picker-view-column`子组件分别渲染了年、月、日三个滚动列。在`data`中初始化了可选的年、月、日数据,以及当前日期的默认值。在`onDateChange`方法中,根据用户选择的年月计算出可选的日数据,并更新`days`和`dateValue`,以便实时渲染出正确的日期选择器。
阅读全文