ref vs templateRef, what's the difference?
What are the differences between ref and templateRef? Is one deprecated?
5 Replies
Hi @Thick Black W. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Short answer:
- ref: Vue’s general reactive reference for any value. Also used in templates as the ref attribute to assign a template ref.
- useTemplateRef: A Vue 3.5 helper to create a typed template ref in <script setup>, especially useful for referencing DOM elements or component instances exposed via defineExpose.
From the Nuxt UI docs and Nuxt repo, guidance has shifted to prefer useTemplateRef for accessing component instances and DOM elements via template refs. Examples show getting typed access to exposed properties like formRef, emblaApi, etc. [Carousel expose; Form expose; Auth form expose; Table expose; Nuxt PR].
Is one deprecated?
- The knowledge sources do not explicitly state that ref is deprecated. They indicate that as of Vue 3.5, useTemplateRef is the recommended way to reference elements/components in templates. [Nuxt PR].
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
<@1321238874634195004> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Hi, template ref is a kind of specialized ref I would say
For referencing a "dom" element
I put dom in quote because it's technically not really dom element if we want to be rigorous
templateRef is basically a
shallowRef, that gets automatically typed for youuseTemplateRef can return arrays of refs for lists.
With useTemplateRef, you can use a variable and template ref name independently