实现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

相关推荐
子兮曰16 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭16 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路19 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒20 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
Kagol21 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉21 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau21 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生21 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼21 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君8799721 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter