vant DatetimePicker 時間選擇年份


由於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;
      },
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM