--- title: Template Refs Are Null Until Mounted impact: HIGH impactDescription: Accessing template ref before mount or after unmount causes runtime errors type: gotcha tags: [vue3, typescript, template-refs, lifecycle, null-safety] --- # Template Refs Are Null Until Mounted **Impact: HIGH** - Template refs have an initial value of `null` and remain null until the component mounts. They can also become null again if the referenced element is removed by `v-if`. Always account for this in TypeScript with union types and optional chaining. ## Task Checklist - [ ] Always type template refs with `| null` union - [ ] Only access refs inside `onMounted` or after - [ ] Use optional chaining (`?.`) when accessing ref properties - [ ] Handle `v-if` scenarios where ref can become null again - [ ] Consider using `useTemplateRef` in Vue 3.5+ ## The Problem ```vue ``` ## The Solution ```vue ``` ## Vue 3.5+: useTemplateRef Vue 3.5 introduces `useTemplateRef` with better type inference: ```vue ``` ## Handling v-if Scenarios Refs can become `null` when elements are conditionally rendered: ```vue ``` ## Component Refs For component refs, use `InstanceType`: ```vue ``` Remember: Child components must use `defineExpose` to expose methods: ```vue ``` ## Multiple Refs with v-for ```vue ``` ## Async Operations and Refs Be careful with async operations: ```vue ``` ## Type Guard Pattern Create a reusable type guard for cleaner code: ```typescript // utils/refs.ts export function assertRef( ref: Ref, message = 'Ref is not available' ): asserts ref is Ref { if (ref.value === null) { throw new Error(message) } } // Usage in component function mustFocus() { assertRef(inputRef, 'Input element not mounted') inputRef.value.focus() // TypeScript knows it's not null here } ``` ## Reference - [Vue.js TypeScript with Composition API - Template Refs](https://vuejs.org/guide/typescript/composition-api.html#typing-template-refs) - [Vue.js Template Refs](https://vuejs.org/guide/essentials/template-refs.html)