組合API:助手函式
useAttrs()
返回從Setup上下文中獲取的attrs
物件,包括當前元件的fallthrough attributes
。這通常用於<script setup>
,其中setup上下文物件不可用。
型別
tsfunction useAttrs(): Record<string, unknown>
useSlots()
返回來自Setup 上下文的 slots
物件,該物件包括作為可呼叫函式傳遞的父級插槽,這些函式返回虛擬DOM節點。這旨在用於<script setup>
,其中不可用setup上下文物件。
如果使用 TypeScript,則應首選使用 defineSlots()
。
型別
tsfunction useSlots(): Record<string, (...args: any[]) => VNode[]>
useModel()
這是defineModel()
背後的輔助工具。如果使用 <script setup>
,則應首選使用 defineModel()
。
僅適用於 3.4+
型別
tsfunction useModel( props: Record<string, any>, key: string, options?: DefineModelOptions ): ModelRef type DefineModelOptions<T = any> = { get?: (v: T) => any set?: (v: T) => any } type ModelRef<T, M extends PropertyKey = string, G = T, S = T> = Ref<G, S> & [ ModelRef<T, M, G, S>, Record<M, true | undefined> ]
示例
jsexport default { props: ['count'], emits: ['update:count'], setup(props) { const msg = useModel(props, 'count') msg.value = 1 } }
詳情
useModel()
可用於非 SFC 元件,例如在使用原始setup()
函式時。它期望props
物件作為第一個引數,模型名稱作為第二個引數。可選的第三個引數可用於宣告自定義的獲取器和設定器,用於生成的模型引用。請注意,與defineModel()
不同,您需要自己宣告 props 和 emits。
useTemplateRef()
返回一個淺引用,其值將與模板元素或具有匹配 ref 屬性的元件同步。
型別
tsfunction useTemplateRef<T>(key: string): Readonly<ShallowRef<T | null>>
示例
vue<script setup> import { useTemplateRef, onMounted } from 'vue' const inputRef = useTemplateRef('input') onMounted(() => { inputRef.value.focus() }) </script> <template> <input ref="input" /> </template>
另請參閱
useId()
用於生成唯一的應用程式 ID,用於無障礙屬性或表單元素。
型別
tsfunction useId(): string
示例
vue<script setup> import { useId } from 'vue' const id = useId() </script> <template> <form> <label :for="id">Name:</label> <input :id="id" type="text" /> </form> </template>
詳情
由
useId()
生成的 ID 具有唯一性。它可以用於生成表單元素和無障礙屬性的 ID。同一組件中的多次呼叫將生成不同的 ID;同一組件的多個例項呼叫useId()
也會生成不同的 ID。由
useId()
生成的 ID 確保在伺服器和客戶端渲染之間保持穩定,因此可以在 SSR 應用程式中使用而不導致水合不匹配。如果您在頁面上有多個相同的 Vue 應用程式例項,可以透過
app.config.idPrefix
給每個應用一個 ID 字首來避免 ID 衝突。