Purpose: Make Vue's template ref (https://vuejs.org/guide/essentials/template-refs.html) more typescript friendly, make IDE suggestion and compiler validator better
Create a file name useRefs.ts in your utils/helpers directory
import { reactive } from 'vue'
export const useRefs = <T extends object>() => {
const refs = reactive<T>({} as T)
const toRef = (refName: keyof T) => (el: any) => ((refs as T)[refName as keyof T] = el)
return {
refs,
toRef,
}
}
Example usage:
<template>
<input :ref="toRef('input')" />
</template>
<script setup lang="ts">
import { onMounted } from 'vue'
import { useRefs } from '@common/utils/useRefs'
const { refs, toRef } = useRefs<{
input: InstanceType<typeof HTMLInputElement>
}>()
onMounted(() => {
refs.input.focus()
})
</script>
What you got:
- No more IDE warning
- IDE suggestion every code with template refs
- Complier checker works with Vue's exposes
We got same idea, that is exactly my first version. However, I got compiler errors when using that for my own Vue component. You can check this official Vue docs for the detail: https://vuejs.org/guide/typescript/composition-api.html#typing-component-template-refs