Concerns around useTemplateRef
and an alternative design
#11408
Replies: 2 comments 3 replies
-
I always found it weird that a variable name had to match with the value of a some attribute down in the But if it hurts tooling capabilities (which I can't judge), I guess that's a really good point. |
Beta Was this translation helpful? Give feedback.
-
There is already an implementation in vue-macros that supports inferring the component types of Note the above usage docs is not up-to-date, to get it working:
Then in {
"vueCompilerOptions": {
"plugins": ["@vue-macros/volar/template-ref"]
}
} We are planning to get this into
// user writes...
useTemplateRef()
// volar transforms it to:
// where ref="foo" and ref="bar" are present in the template
useTemplateRef<unknown, 'foo' | 'bar'>() This means If I'm not misunderstanding, your proposal involves changing the way
The only case where the current One thing to note is that it is already possible to enforce ref type by using function ref values: <script setup lang="ts">
import { shallowRef } from 'vue';
const el = shallowRef<HTMLDivElement | null>()
</script>
<template>
<img :ref="r => el = r" />
^ type error
</template> Here |
Beta Was this translation helpful? Give feedback.
-
Related: vuejs/rfcs#427, 3ba70e4
3.5.0-alpha.3 added
useTemplateRef
, which I'd like to bring up some concerns around its current design.Take the following code example:
There are a few issues with this code:
my_div
, yet in template the ref key ismy_img
by mistake.HTMLDivElement
, yet in template it's aHTMLImageElement
.Some of the issues above can potentially be solved by having special analysis around the usage of
useTemplateRef
, however that only helps in the most trivial cases, and any layer of indirection will break those analysis. For example:Instead, a potential alternative design could be:
templateRef<T>()
which is equivalent toref<T | null>(null)
.ref="foo"
syntax is linked back to thefoo
variable.ref="foo"
syntax.This will solve the above issues:
foo
can be statically analyzed to warn for not used anywhere. In template,ref="bar"
can be statically analyzed to warn forbar
not existing.ref="foo"
to see that the ref type ofHTMLDivElement
does not match the template typeHTMLImageElement
.ref="foo"
in template tofoo
in setup, which allows features such as rename symbol, find references, etc.I believe that the current
useTemplateRef
design hurts the ability to statically analyze to catch problems at compile time and the ability to provide rich tooling features, and an alternative design is worth looking into.Beta Was this translation helpful? Give feedback.
All reactions