由于vant组件自带没有只选择年的方法 所以需要我们自己写这个方法,网上大多数的方法都是通过改node_modules下的组件文件,这个方法不是很友好,下面的方法是我在网上找到一篇可以使用的方法,下附原文地址,原文包括了(年选、月选、周选、日选)方法,这里只用到了年选,因为原文写的年选方法有一点小问题,所以进行了微调改动

原文参考地址:(15条消息) vant 日期选择器(年选、月选、周选、日选)_长夜将尽 来日可期的博客-CSDN博客_vant 日期选择器

本文代码

要点:Field 输入框+ActionSheet 动作面板+DatetimePicker 时间选择 组合使用

我这里的需求是进入页面后默认最新时间所以加上了setTime()里面的方法 如果没有这个需求可以删除setTime()方法

<van-field
v-model="queryParams.taskYear"
is-link
readonly
arrow-direction="down"
label="年份"
placeholder="请选择年份"
@click="dateSelect"
/>
<van-action-sheet v-model="yearShow">
<van-picker
title="请选择年份"
show-toolbar
:columns="yearColumns"
:default-index="yearSelect"
@confirm="yearConfirm"
@cancel="cancel"
/>
</van-action-sheet>
export default {
data() {
return {
// 查询参数
queryParams: {
taskYear: null,
},
yearSelect: null,
yearColumns: [],
yearShow:false // 年份
}
}
created() {
this.setTime();
this.yearData();
},
methods: {
formatDates(date) {
return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;
},
// 进入页面后默认最新时间
setTime(){
var nowTime = new Date();
let year = nowTime.getFullYear();
let month = nowTime.getMonth();
let day = nowTime.getDate();
var taskYear = '';
taskYear = this.formatDates( new Date(year, month ,day));
this.queryParams.taskYear = taskYear.slice(0,4);
}
// 监听年份打开
dateSelect() {
this.yearShow = true;
},
//年选择器
yearConfirm(value) {
this.queryParams.taskYear = value.toString();
this.yearShow = false;
},
//年数据
yearData() {
// 获取默认显示的时间
var nowTime = new Date(this.queryParams.taskYear);
let year = nowTime.getFullYear();
let month = nowTime.getMonth();
let day = nowTime.getDate();
// 循环数组 填写最小时间和最大时间范围 推进数组
for (let i = 2000; i < 2099; i++) {
this.yearColumns.push(i);
}
// 格式化时间并截取
var years = this.formatDates( new Date(year, month ,day));
var Year = years.slice(0,4);
// 将截取的年份赋值给绑定值 用于点击弹出日期窗口后显示当前的时间
this.yearSelect = this.yearColumns.indexOf(Number(Year));
},
// 点击取消按钮时触发的事件
cancel() {
this.yearShow = false;
},
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。