自学内容网 自学内容网

实现vant的年月日时分秒组件

方法:van-datetime-picker(type:datetime)和 van-picker结合实现。

<template>
  <div class="datetimesec-picker">
    <van-datetime-picker
      ref="timePickerRef"
      type="datetime" //年月日时分
      v-model="currentDate"
      :show-toolbar="false"
      :visible-item-count="7"
      @confirm="onTimeConfirm"
    />
    <van-picker
      class="sec-picker"
      :default-index="secondIdx"
      :show-toolbar="false"
      :visible-item-count="7"
      :columns="
        Array(60)
        .fill()
        .map((_, i) => `0${i}`.slice(-2))
       " //秒
      @change="handleSecChange"
    />
  </div>
  <div @click="toggleTimeConfirm">
    <span class="flex justify-center items-center fw-600 text-18px c-#fff">
      下一步
    </span>
  </div>
</template>

<script setup>
import momentMini from 'moment-mini'

const formData = reactive({
  startDate:momentMini(new Date()).subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
})
const timePickerRef = ref(null)
const currentDate = ref(
  new Date(new Date().getTime() - 1 * 24 * 60 * 60 * 1000),
) //默认往前1天
const secondIdx = ref(null) //默认秒数索引
const handleSecChange = (val, idx) => {
  secondIdx.value = idx
}

watch(
  () => formData.startDate,
  nV => {
    secondIdx.value = Number(nV.slice(-2))
  },
  { immediate: true },
)

//点击‘下一步’
const toggleTimeConfirm= () => {
  //触发datetime-picker的confirm钩子
  timePickerRef.value.getPicker().confirm()
}
const onTimeConfirm= value => {
  formData.startDate= `${momentMini(new Date(value))
    .format('YYYY-MM-DD HH:mm:ss')
    .slice(0, -2)}${addZero(secondIdx.value)}`
}

// 一位数字前面补零
const addZero = (num) => {
  return num < 10 ? `0${num}` : num;
}
</script>

<style lang="scss" scoped>
.datetimesec-picker {
  display: flex;
  .van-picker:first-of-type {
    flex: 5;
  }
  .van-picker:last-of-type {
    flex: 1;
  }
}
</style>

参考文章:

van-datetimesec-picker - npm


原文地址:https://blog.csdn.net/weixin_45346457/article/details/138523235

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!