Vuetify 3 Datepicker键盘模式下如何监听日期输入?
Vuetify 3 键盘模式日期选择器正确使用方法
你的代码中@update:modelValue事件无法触发,核心原因是键盘模式下的v-date-picker不会实时触发更新事件,只有当用户完成输入确认(比如按下回车、点击组件外部),且输入的日期格式符合组件预期时,才会触发@update:modelValue。
以下是两种正确的使用方案:
方案1:使用v-model语法糖(推荐)
v-model是Vue的双向绑定语法糖,会自动处理model-value的绑定和@update:modelValue事件监听,代码更简洁且不易出错:
<script setup lang="ts"> import { ref } from "vue"; const currentDate = ref(new Date()); function onNewDate(newDate) { console.log("-- I have been called --"); currentDate.value = newDate; } </script> <template> <v-app> <v-date-picker input-mode="keyboard" input-placeholder="按区域设置的特定格式输入" input-text="选择日期" hide-header v-model="currentDate" @update:modelValue="onNewDate" /> </v-app> </template>
方案2:手动监听输入确认事件(精细控制)
如果需要在用户输入过程中做额外处理,可以监听输入框的blur(失焦)或keydown.enter(回车)事件,手动解析并更新日期值:
<script setup lang="ts"> import { ref } from "vue"; const currentDate = ref(new Date()); const inputText = ref(""); function confirmDate() { const parsedDate = new Date(inputText.value); if (!isNaN(parsedDate.getTime())) { currentDate.value = parsedDate; console.log("-- I have been called --"); } else { console.error("输入的日期格式无效"); } } </script> <template> <v-app> <v-date-picker input-mode="keyboard" input-placeholder="按区域设置的特定格式输入" input-text="选择日期" hide-header :model-value="currentDate" :input-value="inputText" @update:input-value="inputText = $event" @blur="confirmDate" @keydown.enter="confirmDate" /> </v-app> </template>
关键注意事项
- 键盘模式下,
@update:modelValue仅在日期格式有效+用户确认输入时触发,不会随输入字符实时触发。 - 可以通过
format属性自定义日期格式(比如format="DD/MM/YYYY"),确保输入格式与组件预期匹配,否则更新事件不会触发。 - 若无需额外逻辑,直接使用
v-model="currentDate"即可,无需手动绑定@update:modelValue。
内容的提问来源于stack exchange,提问作者baitendbidz
相关产品推荐
相关产品推荐

