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