使用Vant的DatetimePicker時間選擇組件


安裝vant

# 通過 npm 安裝
npm i vant -S

在main.js中引入vant

// 引入vant
import Vant from 'vant'
import 'vant/lib/index.css'

Vue.use(Vant)

使用DatetimePicker組件

確認選擇的時間數據是需要自己處理的,詳見confirmPicker方法

<template>
  <div class="seller">
    <van-cell
      title="開始時間"
      is-link
      :value-class="className"
      :value="timeValue"
      @click="showPopup" />
    <van-popup v-model="show" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="選擇時間"
        :loading="isLoadingShow"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @cancel="show = false"
        @confirm="confirmPicker"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'Seller',
  data () {
    return {
      msg: '商家頁面',
      timeValue: '請選擇時間',
      show: false,
      isLoadingShow: true,
      currentDate: new Date(),
      minDate: new Date(),
      maxDate: new Date(2020, 12, 31),
      className: ''
    }
  },
  methods: {
    // 顯示彈窗
    showPopup () {
      this.show = true
      this.isLoadingShow = true
      setTimeout(() => {
        this.isLoadingShow = false
      }, 500)
    },
    // 確認選擇的時間
    confirmPicker (val) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      if (month >= 1 && month <= 9) { month = `0${month}` }
      if (day >= 1 && day <= 9) { day = `0${day}` }
      if (hour >= 0 && hour <= 9) { hour = `0${hour}` }
      if (minute >= 0 && minute <= 9) { minute = `0${minute}` }
      this.className = 'timeClass'
      this.timeValue = `${year}-${month}-${day} ${hour}:${minute}`
      this.show = false
    },
    // 選項格式化函數
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}時`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
.seller
  .timeClass {
    color: #333;
  }
</style>

實際效果

如有錯誤,請多指教,謝謝!


免責聲明!

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



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