方法: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>
参考文章: