van-datetime-picker只显示年份(改造后)

2025年01月20日 建站教程

项目搭建用的vant组件库,但是vant官网上DatetimePicker时间组件van-datetime-picker没有单独显示年份的组件,下面给大家介绍一下改造后的代码!

template代码

<van-cell-group>
  <van-field  readonly clickable placeholder="请选择年份" :value="dateValue" @click="showPicker = true" />
  <van-popup v-model="showPicker" round position="bottom">
  <van-picker title="请选择年份" show-toolbar :columns="columns" :default-index="select" @confirm="yearConfirm" @cancel="cancel" />
  </van-popup>
</van-cell-group>

script代码

data() {
  return {
  dateValue: '',
  showPicker: false,
  select: null,
  columns: []
  }
},
created() {
  this.getCurrentYear()
  this.getYearData()
},
methods: {
  formatDates(date) {
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
  },
  //获取默认最新时间
  getCurrentYear() {
    var nowTime = new Date()
    let year = nowTime.getFullYear()
    let month = nowTime.getMonth()
    let day = nowTime.getDate()
    var dateValue = ''
    dateValue = this.formatDates(new Date(year, month, day))
    this.dateValue = dateValue.slice(0, 4)
    this.signs(this.dateValue)
  },
  //年选择器
  yearConfirm(value) {
    this.dateValue = value.toString()
    this.signs(this.dateValue)
    this.showPicker = false
  },
  //年数据
  getYearData() {
    var nowTime = new Date(this.dateValue)
    let year = nowTime.getFullYear()
    let month = nowTime.getMonth()
    let day = nowTime.getDate()
    for (let i = 1901; i < 2099; i++) {
    this.columns.push(i)
    }

    var years = this.formatDates(new Date(year, month, day))
    var Year = years.slice(0, 4)

    this.select = this.columns.indexOf(Number(Year))
  },
  //点击取消按钮时触发的事件
  cancel() {
    this.showPicker = false
  }
}

本文链接:http://so.lmcjl.com/news/21706/

展开阅读全文
相关内容