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

相关推荐
可乐鸡翅yeah_36 分钟前
hls.js 手动自定义 http 请求 loader,修改请求头实战
开发语言·前端·javascript·网络协议·http·ecmascript·m3u8在线
IT_陈寒1 小时前
Vite静态资源导入这个坑我帮你们踩过了
前端·人工智能·后端
广州华水科技1 小时前
大坝安全监测解决方案:单北斗GNSS形变监测系统应用与维护
前端
yivifu2 小时前
中文古籍电子书注释集成
前端·javascript·python·beautifulsoup·epub
weixin_448290252 小时前
书庐开发实战教学
javascript·css·html
默_笙2 小时前
🛴 从散件到整机:DeepAgents 与 Agent 身上预留的那些"插槽"(前置介绍)
前端·javascript
zhangzeyuaaa3 小时前
深入理解 Ruby 运算符:本质、分类、坑点与重载实战
开发语言·前端·ruby
一木 之林3 小时前
DeepSeek Agent 开发(一)
开发语言·前端·javascript
树下水月4 小时前
Typora破解
linux·服务器·前端
用户5508492902564 小时前
CSS布局实战:从Flex到Grid的完整避坑指南
前端