2024/04/17

Vuetify date picker 的雷

 

我這 blog 已經 8 年多沒更新了,今天花了快 1 小時解這問題,終於被我試出一個莫名奇妙的 workaround,一定要來發一篇文章,或許可以幫到某個跟我遇到一樣蝦的問題的人。

在使用 Vuetify 的 v-date-picker 時,遇到一個非常奇粑的問題,當我們點擊 v-text-field 時,預期要出現 date picker,可以選擇日期,但是偏偏在點選旁邊一點的位置時,會發現 v-text-field 有反應,label 的動畫會跑,



以下是原本實作的 code:

<template>
<v-menu
v-model="showPicker"
:close-on-content-click="false"
>
<template v-slot:activator="{ props }">
<v-text-field
clearable
:label="label"
v-model="formattedDate"
v-bind="props"
:format="dateFormat"
variant="outlined"
hint="YYYY-MM-DD"
persistent-hint
prepend-inner-icon="mdi-calendar"
@click:clear="clearDate"
@input="onTextInput"
density="compact"
hide-details
></v-text-field>
</template>
<div>
<v-date-picker
v-model="date"
></v-date-picker>
</div>
</v-menu>
</template>

幾次嘗試之後,一直想要抓到是哪個 event 造成這樣的差異,後來發現主要是 focus 與 click 的行為的不同。



接著試著在 focus 的 event 中,來觸發 date picker 的顯示:

<v-text-field
clearable
:label="label"
v-model="formattedDate"
v-bind="props"
:format="dateFormat"
variant="outlined"
hint="YYYY-MM-DD"
persistent-hint
prepend-inner-icon="mdi-calendar"
@click:clear="clearDate"
@focus="showPicker = true"
@input="onTextInput"
density="compact"
hide-details
></v-text-field>

卻發現結果原先正常的 text input 區塊,點擊後反而閃退…



猜測原因是原先 date picker 有實作 toggle (切換),但剛好前一刻才透過 focus 設成 true,下一刻可能就被 toggle 關成 false。

先傻眼了 10 秒,最後突發奇想的,那就再設一個 click 的 event,會不會能"負負得正"?

<template v-slot:activator="{ props }">
<v-text-field
clearable
:label="label"
v-model="formattedDate"
v-bind="props"
:format="dateFormat"
variant="outlined"
hint="YYYY-MM-DD"
persistent-hint
prepend-inner-icon="mdi-calendar"
@click:clear="clearDate"
@focus="showPicker = true"
@input="onTextInput"
@click="showPicker = true"
density="compact"
hide-details
></v-text-field>
</template>

想不到居然可以!


雖然在 text input 區域之外的地方,點擊後經過 toggle 還是會變成無法再次開啟,而且原先 text input 的地方,變成無法 toggle,但至少在第一次點擊到這個日期編輯區時,不會因為 date picker 沒出現而覺得困擾了…

這做法蠻瞎的,但這問題我的前端夥伴卡了蠻久,我接手嘗試解決,也只能做到這樣,特別記錄一下!

My World