Kurs Vue.js · Moduł 15: TypeScript i Nuxt
Projekt Główny: Typowany Panel Stacji NOVA LAB
W tej lekcji6
Czas połączyć całą wiedzę z tego modułu! Stworzymy typowany panel sterowania stacją kosmiczną NOVA LAB, który wykorzystuje TypeScript z Vue 3 i uwzględnia koncepcje SSR.
Wymagania projektu
Nasz panel sterowania powinien zawierać:
- Typowane propsy - każdy komponent deklaruje jakie dane przyjmuje
- Typowane emity - zdarzenia są precyzyjnie zdefiniowane
- Typowane ref i reactive - stan aplikacji jest w pełni typowany
- Template refs - do bezpośredniej interakcji z DOM
- Provide/Inject - do przekazywania konfiguracji stacji
Architektura aplikacji
// types.ts - centralne typy aplikacji
interface CrewMember {
id: number
name: string
role: 'commander' | 'engineer' | 'scientist' | 'pilot'
active: boolean
}
interface StationModule {
id: string
name: string
status: 'online' | 'offline' | 'maintenance'
power: number
}
interface StationState {
name: string
crew: CrewMember[]
modules: StationModule[]
alerts: Alert[]
}
interface Alert {
id: number
level: 'info' | 'warning' | 'critical'
message: string
timestamp: Date
}Komponent ModuleCard z typami
<script setup lang="ts">
interface ModuleCardProps {
module: StationModule
isSelected?: boolean
}
const props = withDefaults(defineProps<ModuleCardProps>(), {
isSelected: false
})
const emit = defineEmits<{
select: [moduleId: string]
togglePower: [moduleId: string, newStatus: boolean]
}>()
</script>Panel z Provide/Inject
<script setup lang="ts">
import { provide, reactive, type InjectionKey } from 'vue'
interface StationConfig {
name: string
sector: string
year: number
}
const StationKey: InjectionKey<StationConfig> = Symbol('Station')
provide(StationKey, {
name: 'NOVA LAB',
sector: 'Alpha-7',
year: 2087
})
</script>Uwzględnienie SSR
Tworząc aplikację z myślą o SSR (np. z Nuxt), pamiętaj:
// NIE używaj obiektów przeglądarki poza onMounted
import { onMounted, ref } from 'vue'
const windowWidth = ref(0)
// DOBRZE - window dostępne tylko na kliencie
onMounted(() => {
windowWidth.value = window.innerWidth
})
// ZLE - window nie istnieje na serwerze!
// const width = window.innerWidth // BLAD w SSRComposable przyjazny SSR:
function useScreenSize() {
const width = ref(0)
const height = ref(0)
onMounted(() => {
width.value = window.innerWidth
height.value = window.innerHeight
window.addEventListener('resize', () => {
width.value = window.innerWidth
height.value = window.innerHeight
})
})
return { width, height }
}Pełny przykład
Poniżej znajduje się interaktywny edytor z typowaną aplikacją Vue. Przeanalizuj kod i eksperymentuj z typami - dodaj nowe właściwości, zmień typy i obserwuj jak TypeScript pomaga wykrywać błędy.
Kod do tej lekcji: App.vue
<script setup lang="ts">
import { ref, reactive, computed, provide, type InjectionKey } from 'vue'
import ModuleList from './ModuleList.vue'
import AlertPanel from './AlertPanel.vue'
// ===== Typy =====
interface CrewMember {
id: number
name: string
role: 'commander' | 'engineer' | 'scientist' | 'pilot'
active: boolean
}
interface StationModule {
id: string
name: string
status: 'online' | 'offline' | 'maintenance'
power: number
}
interface Alert {
id: number
level: 'info' | 'warning' | 'critical'
message: string
}
interface StationConfig {
name: string
sector: string
year: number
}
// ===== Provide =====
const StationKey: InjectionKey<StationConfig> = Symbol('Station')
provide(StationKey, { name: 'NOVA LAB', sector: 'Alpha-7', year: 2087 })
// ===== Stan =====
const modules = ref<StationModule[]>([
{ id: 'm1', name: 'Life Support', status: 'online', power: 95 },
{ id: 'm2', name: 'Navigation', status: 'online', power: 88 },
{ id: 'm3', name: 'Science Lab', status: 'maintenance', power: 40 },
{ id: 'm4', name: 'Communications', status: 'offline', power: 0 },
{ id: 'm5', name: 'Power Grid', status: 'online', power: 72 }
])
const alerts = ref<Alert[]>([
{ id: 1, level: 'info', message: 'System started' },
{ id: 2, level: 'warning', message: 'Module m3 w trybie konserwacji' }
])
let alertId = 3
// ===== Computed =====
const onlineCount = computed(() => modules.value.filter(m => m.status === 'online').length)
const avgPower = computed(() => {
const online = modules.value.filter(m => m.status === 'online')
if (online.length === 0) return 0
return Math.round(online.reduce((s, m) => s + m.power, 0) / online.length)
})
// ===== Metody =====
function handleToggle(moduleId: string) {
const mod = modules.value.find(m => m.id === moduleId)
if (!mod) return
mod.status = mod.status === 'online' ? 'offline' : 'online'
mod.power = mod.status === 'online' ? 80 : 0
alerts.value.push({
id: alertId++,
level: mod.status === 'online' ? 'info' : 'warning',
message: mod.name + ' ' + (mod.status === 'online' ? 'wlaczony' : 'wylaczony')
})
}
function dismissAlert(id: number) {
alerts.value = alerts.value.filter(a => a.id !== id)
}
</script>
<template>
<div class="nova-lab">
<header class="header">
<h1>NOVA LAB - Typowany Panel</h1>
<div class="stats">
<span class="stat">Online: {{ onlineCount }}/{{ modules.length }}</span>
<span class="stat">Avg Power: {{ avgPower }}%</span>
</div>
</header>
<AlertPanel :alerts="alerts" @dismiss="dismissAlert" />
<ModuleList :modules="modules" @toggle="handleToggle" />
</div>
</template>
<style scoped>
.nova-lab {
background: #0a0e27;
color: #00ff88;
min-height: 100vh;
padding: 20px;
font-family: monospace;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
border-bottom: 1px solid rgba(0,180,216,0.3);
padding-bottom: 12px;
}
h1 { color: #00ff88; margin: 0; font-size: 18px; }
.stats { display: flex; gap: 15px; }
.stat {
background: rgba(0,180,216,0.1);
padding: 6px 12px;
border-radius: 6px;
font-size: 12px;
color: #00b4d8;
}
</style>Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?