javascript
/**
* 日期时间输入框格式化(按你的逻辑)
* 支持:20160908120912 → 2016-09-08 12:09:12
* 支持:实时格式化
*/
export function handleDateTimeKeydown(e, formData, field) {
// 1. 只允许数字 + 控制键
const isNumber = /^[0-9]$/.test(e.key)
const isControl = ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'].includes(e.key)
if (!isNumber && !isControl) {
e.preventDefault()
return
}
if (isControl) return
// 2. 异步格式化
setTimeout(() => {
const input = e.target
let val = input.value.replace(/\D/g, '') // 只留数字
if (val.length < 8) return
// 3. 拆分日期 + 时间
const date = val.slice(0, 8)
const time = val.slice(8, 14)
// 4. 格式化日期
const y = date.slice(0, 4)
const m = date.slice(4, 6)
const d = date.slice(6, 8)
let dateStr = `${y}-${m}-${d}`
// 5. 格式化时间(完全按你的逻辑)
let timeStr = ''
if (time.length >= 1) timeStr = time.slice(0, 1)
if (time.length >= 2) timeStr = time.slice(0, 2)
if (time.length >= 3) timeStr = time.slice(0, 2) + ':' + time.slice(2, 3)
if (time.length >= 4) timeStr = time.slice(0, 2) + ':' + time.slice(2, 4)
if (time.length >= 5) timeStr = time.slice(0, 2) + ':' + time.slice(2, 4) + ':' + time.slice(4, 5)
if (time.length >= 6) timeStr = time.slice(0, 2) + ':' + time.slice(2, 4) + ':' + time.slice(4, 6)
// 最终内容
let final = dateStr
if (timeStr) final += ' ' + timeStr
// 强制显示
input.value = final
// 输满14位 → 同步到 v-model
if (val.length === 14 && formData && field) {
formData[field] = final
}
}, 0)
}
使用方法:使用@keydown来进行触发
javascript
<el-date-picker
v-model="formData.startTime"
type="datetime"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
style="width: 100%"
placeholder="请选择时间"
@keydown="(e) => handleDateTimeKeydown(e, formData, 'startTime')"
/>