Vue.js course ยท Module 15: TypeScript & Nuxt
Template Refs and Provide/Inject with Types
In this lesson4
In the advanced NOVA LAB station systems, we sometimes need to directly reference DOM elements or pass data between components without props drilling. TypeScript helps us do this safely.
Template Refs with Types
A template ref allows you to get a reference to a DOM element:
<script setup lang="ts">
import { ref, onMounted } from 'vue'
// HTML element type - ref can be null before mounting
const inputRef = ref<HTMLInputElement | null>(null)
const canvasRef = ref<HTMLCanvasElement | null>(null)
onMounted(() => {
// After mounting, ref is no longer null
inputRef.value?.focus()
const ctx = canvasRef.value?.getContext('2d')
if (ctx) {
ctx.fillStyle = '#00ff88'
ctx.fillRect(0, 0, 100, 100)
}
})
</script>
<template>
<input ref="inputRef" placeholder="Enter command..." />
<canvas ref="canvasRef" width="400" height="300" />
</template>The type HTMLInputElement | null tells TypeScript that the ref can be null (before the component is mounted).
Component References
You can also get a reference to a child component:
<script setup lang="ts">
import { ref } from 'vue'
import SensorPanel from './SensorPanel.vue'
// InstanceType<typeof Component> gives the component instance type
const sensorRef = ref<InstanceType<typeof SensorPanel> | null>(null)
function refreshSensors() {
// Access public methods of the component
sensorRef.value?.refresh()
}
</script>
<template>
<SensorPanel ref="sensorRef" />
<button @click="refreshSensors">Refresh Sensors</button>
</template>InjectionKey and Provide/Inject
provide/inject allows passing data down the component tree. InjectionKey<T> ensures type safety:
<!-- types.ts -->
<script lang="ts">
import type { InjectionKey, Ref } from 'vue'
export interface StationConfig {
name: string
maxCrew: number
sector: string
}
// Key with type - ensures provide and inject use the same type
export const StationConfigKey: InjectionKey<StationConfig> = Symbol('StationConfig')
export const ThemeKey: InjectionKey<Ref<'dark' | 'light'>> = Symbol('Theme')
</script><!-- Provider (parent) -->
<script setup lang="ts">
import { provide, ref } from 'vue'
import { StationConfigKey, ThemeKey } from './types'
const theme = ref<'dark' | 'light'>('dark')
provide(StationConfigKey, {
name: 'NOVA LAB',
maxCrew: 100,
sector: 'Alpha-7'
})
provide(ThemeKey, theme)
</script><!-- Consumer (child/grandchild) -->
<script setup lang="ts">
import { inject } from 'vue'
import { StationConfigKey, ThemeKey } from './types'
// TypeScript knows the type! StationConfig | undefined
const config = inject(StationConfigKey)
// With a default value - it's not undefined
const theme = inject(ThemeKey, ref('dark'))
// We use optional chaining because config can be undefined
console.log(config?.name) // 'NOVA LAB'
console.log(theme.value) // 'dark'
</script>Pattern with Default Value
To avoid undefined, you can use a default value:
const config = inject(StationConfigKey, {
name: 'Unknown',
maxCrew: 0,
sector: 'N/A'
})
// Now config is always StationConfig (never undefined)You can also use a factory function:
const config = inject(StationConfigKey, () => ({
name: 'Default',
maxCrew: 50,
sector: 'Beta'
}), true) // third arg = true means it's a factory functionCode for this lesson: App.vue
<script setup lang="ts">
import { ref, provide, onMounted, type InjectionKey } from 'vue'
import InfoPanel from './InfoPanel.vue'
// --- Template Ref ---
const searchInput = ref<HTMLInputElement | null>(null)
const searchQuery = ref('')
onMounted(() => {
// After mounting - focus the input
searchInput.value?.focus()
})
function clearSearch() {
searchQuery.value = ''
searchInput.value?.focus()
}
// --- InjectionKey ---
interface StationConfig {
name: string
sector: string
year: number
}
const StationConfigKey: InjectionKey<StationConfig> = Symbol('StationConfig')
// Provide with a type
provide(StationConfigKey, {
name: 'NOVA LAB',
sector: 'Alpha-7',
year: 2087
})
// Export the key so the child can use it
provide('configKey', StationConfigKey)
</script>
<template>
<div class="nova-lab">
<h1>Template Refs & Provide/Inject</h1>
<div class="search-box">
<input
ref="searchInput"
v-model="searchQuery"
placeholder="Search station systems..."
class="search-input"
/>
<button @click="clearSearch" class="btn">Clear</button>
</div>
<p v-if="searchQuery" class="query-info">
Searching: <strong>{{ searchQuery }}</strong>
</p>
<InfoPanel />
</div>
</template>
<style scoped>
.nova-lab {
background: #0a0e27;
color: #00ff88;
min-height: 100vh;
padding: 20px;
font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 15px; }
.search-box { display: flex; gap: 8px; margin-bottom: 10px; }
.search-input {
flex: 1;
background: rgba(0,180,216,0.1);
border: 2px solid #00b4d8;
color: #00ff88;
padding: 10px 14px;
border-radius: 8px;
font-family: monospace;
font-size: 14px;
outline: none;
}
.search-input:focus { border-color: #00ff88; }
.btn {
background: #00b4d8;
color: white;
border: none;
padding: 10px 16px;
border-radius: 8px;
cursor: pointer;
}
.query-info { color: #00b4d8; font-size: 13px; }
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Why do we define a template ref as
ref<HTMLInputElement | null>(null)?2. What does InjectionKey<T> provide in the provide/inject system?
Hands-on tasks in the game
- Vertical ordering
Arrange the steps for working with a typed template ref:
- Code editor
Define an InjectionKey, use provide in the parent and inject in the child.
- Click in order
Arrange the steps for creating typed provide/inject:
- Horizontal ordering
Arrange the syntax for a typed component reference: