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

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

javascript 复制代码
<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

相关推荐
用户69371750013843 分钟前
DeepSeek 调价正式生效:一夜涨 11 倍,靠低价薅羊毛的日子结束了
前端·人工智能·后端
Orange_sparkle6 分钟前
从五个 TypeScript 文件看懂 Coding Agent:一次 nano-pi 学习复盘
javascript·学习·typescript
半仙er9 分钟前
第一周01天:this 指向与 call / apply / bind
前端
小帅不太帅10 分钟前
给大家推荐一个特别好用的专为 AI Agent 打造的最快浏览器
前端·agent·浏览器
半仙er10 分钟前
第一周03天 事件循环与宏任务 / 微任务
前端
做前端的娜娜子13 分钟前
#浏览器存储方案:localStorage、sessionStorage 与 Cookie
前端·面试·掘金·金石计划
用户9210802628623 分钟前
1. Ant Design X Vue 项目介绍:结构、组件和启动方式
前端
摸鱼研究员24 分钟前
neverthrow,ts 中优雅的异常处理方案
前端·javascript
烬羽25 分钟前
求第 K 大,为什么反而要用最小堆?
javascript·数据结构·算法
jingchao199829 分钟前
Cannot read properties of null (reading ‘insertBefore‘)
前端·javascript·vue.js