我正在使用 Composition API (with <script setup lang='ts'>) 創建一個 ref,在我的模板中使用:
const searchRef = ref(null)
onMounted(() => { searchRef.value.focus() })
它確實有效,我的代碼編譯沒有錯誤。然而,IDE(JetBrains Goland 或 Webstorm)抱怨TS2531: Object is possibly 'null'..
核心解決方案是使用
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Object is possibly 'null'.
但我想了解是否有更好的方法。
我希望可選鏈接是一個解決方案:
const searchRef = ref(null)
onMounted(() => { searchRef.value?.focus() })
代碼仍然可以編譯并且應用程式仍然可以作業,但我現在有了 TS2339: Property 'focus' does not exist on type 'never'.
解決這個問題的正確方法是什么?
uj5u.com熱心網友回復:
對于模板參考,將泛型型別引數傳遞給refat 初始化。泛型型別應與模板 ref 的目標元素的型別相匹配。
以下是原生 HTML 元素上的模板參考的一些示例:
const htmlElemRef = ref<HTMLElement>() // => type: HTMLElement | undefined
const inputRef = ref<HTMLInputElement>() // => type: HTMLInputElement | undefined
const textareaRef = ref<HTMLTextAreaElement>() // => type: HTMLTextAreaElement | undefined
該null初始化是可選的,我常常忽略它稍微更簡潔的代碼。結果型別為<T | undefined>,這比null因為模板中不存在元素時ref實際為 更正確undefined。ref的值仍然需要可選鏈接(假設它可能是undefined)。
例子:
const searchRef = ref<HTMLInputElement>()
onMounted(() => { searchRef.value?.focus() })
正如@Kurt 指出的那樣,Vue 組件上的模板參考需要不同的型別。的泛型型別ref將是InstanceType組件型別的一個(來自.vue匯入):
InstanceType<typeof MyComponentDefinition>
例子:
import HelloWorld from '@/components/HelloWorld.vue'
const helloRef = ref<InstanceType<typeof HelloWorld>>()
演示
uj5u.com熱心網友回復:
解決此問題的一種可能方法是手動添加正確的型別:
const searchRef: Ref<HTMLElement | null> = ref(null);
onMounted(() => { searchRef.value?.focus() });
注意:如果參考針對 Vue 組件(例如Ref<HTMLElement | Vue | null>),則 HTMLElement 可能會有所不同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344807.html
標籤:打字稿 Vue.js 参考 Vuejs3 vue-composition-api
下一篇:如何拼接多個陣列元素并相應插入?
