章節連結
Vue3 在實作失焦時觸發某個函式時,需先有「聚焦」的行為。因此你在點擊某個按鈕後,要幫使用者自動聚焦到指定的 input 上,否則會發生預期外的行為。
內容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
const value = ref('') const nameDom = ref<HTMLInputElement | null> const handleTriggerEdit = async ({ targetKey }: { targetKey: 'name' }) => { // 使用 nextTick 確保 DOM 已更新後再執行 focus await nextTick() // 自動設定焦點到對應的輸入框 const inputMap: Record<'name', Ref<HTMLInputElement | null>> = { name: nameDom, } const inputElement = inputMap[targetKey]?.value if (inputElement) { inputElement.focus() } } <input v-model="value" ref=nameDom type="text" min="1" class="mx-2 w-10 p-1 text-center focus:ring-0" @blur="handleInputBlur({ targetKey: 'name' })" /> |
按讚加入粉絲團