Kurs Vue.js · Moduł 15: TypeScript i Nuxt
Template Refs i Provide/Inject z typami
W tej lekcji4
W zaawansowanych systemach stacji NOVA LAB musimy czasem bezpośrednio odwoływać się do elementow DOM lub przekazywać dane między komponentami bez props drilling. TypeScript pomaga nam robić to bezpiecznie.
Template Refs z typami
Template ref pozwala uzyskać referencję do elementu DOM:
<script setup lang="ts">
import { ref, onMounted } from 'vue'
// Typ elementu HTML - ref może być null przed montowaniem
const inputRef = ref<HTMLInputElement | null>(null)
const canvasRef = ref<HTMLCanvasElement | null>(null)
onMounted(() => {
// Po montowaniu ref nie jest już 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="Wpisz komendę..." />
<canvas ref="canvasRef" width="400" height="300" />
</template>Typ HTMLInputElement | null mówi TypeScriptowi, że ref może być null (zanim komponent zostanie zamontowany).
Referencje do komponentów
Można też uzyskać referencję do komponentu dziecka:
<script setup lang="ts">
import { ref } from 'vue'
import SensorPanel from './SensorPanel.vue'
// InstanceType<typeof Component> daje typ instancji komponentu
const sensorRef = ref<InstanceType<typeof SensorPanel> | null>(null)
function refreshSensors() {
// Dostęp do publicznych metod komponentu
sensorRef.value?.refresh()
}
</script>
<template>
<SensorPanel ref="sensorRef" />
<button @click="refreshSensors">Odśwież sensory</button>
</template>InjectionKey i Provide/Inject
provide/inject pozwala przekazywać dane w dół drzewa komponentów. InjectionKey<T> zapewnia bezpieczeństwo typów:
<!-- types.ts -->
<script lang="ts">
import type { InjectionKey, Ref } from 'vue'
export interface StationConfig {
name: string
maxCrew: number
sector: string
}
// Klucz z typem - zapewnia że provide i inject używają tego samego typu
export const StationConfigKey: InjectionKey<StationConfig> = Symbol('StationConfig')
export const ThemeKey: InjectionKey<Ref<'dark' | 'light'>> = Symbol('Theme')
</script><!-- Provider (rodzic) -->
<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 (dziecko/wnuk) -->
<script setup lang="ts">
import { inject } from 'vue'
import { StationConfigKey, ThemeKey } from './types'
// TypeScript zna typ! StationConfig | undefined
const config = inject(StationConfigKey)
// Z wartością domyślną - nie jest undefined
const theme = inject(ThemeKey, ref('dark'))
// Używamy optional chaining bo config może być undefined
console.log(config?.name) // 'NOVA LAB'
console.log(theme.value) // 'dark'
</script>Wzorzec z wartością domyślną
Aby uniknąć undefined, można użyć wartości domyślnej:
const config = inject(StationConfigKey, {
name: 'Unknown',
maxCrew: 0,
sector: 'N/A'
})
// Teraz config jest zawsze StationConfig (nigdy undefined)Można też użyć funkcji fabrykującej:
const config = inject(StationConfigKey, () => ({
name: 'Default',
maxCrew: 50,
sector: 'Beta'
}), true) // trzeci arg = true oznacza że to factory functionKod do tej lekcji: 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(() => {
// Po zamontowaniu - focus na 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 z typem
provide(StationConfigKey, {
name: 'NOVA LAB',
sector: 'Alpha-7',
year: 2087
})
// Eksportujemy klucz aby dziecko moglo go uzyc
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="Szukaj w systemach stacji..."
class="search-input"
/>
<button @click="clearSearch" class="btn">Wyczysc</button>
</div>
<p v-if="searchQuery" class="query-info">
Szukasz: <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>Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Dlaczego template ref definiujemy jako
ref<HTMLInputElement | null>(null)?2. Co zapewnia InjectionKey<T> w systemie provide/inject?
Zadania praktyczne w grze
- Układanie w pionie
Uporządkuj kroki pracy z typowanym template ref:
- Edytor kodu
Zdefiniuj InjectionKey, użyj provide w rodzicu i inject w dziecku.
- Klikanie w kolejności
Ułóż kroki tworzenia typowanego provide/inject:
- Układanie w poziomie
Ułóż składnię typowanej referencji do komponentu: