Kurs Vue.js · Moduł 11: Pinia

Projekt: System Zasobów NOVA LAB

2 min czytania ·
W tej lekcji3

Czas zastosować całą wiedzę o Pinia w jednym projekcie! Zbudujesz kompletny system zarządzania zasobami stacji NOVA LAB, który wykorzystuje:

  • Store z state - przechowywanie danych o zasobach (tlen, woda, energia)
  • Getters - wyliczanie statusów, alertów, statystyk
  • Actions - operacje CRUD, zużycie zasobów, alarmy
  • Kompozycja stores - resource store + alert store
  • $subscribe - monitorowanie zmian

Architektura projektu

stores/
├── resources.js     # Zasoby stacji (state, getters, actions)
└── alerts.js        # System alertów (subscribe do resources)

Przepływ danych

ResourceStore (state: oxygen, water, energy)
  ├── getters → statusLevel, criticalResources, summary
  ├── actions → consume(), refill(), emergencyProtocol()
  └── $subscribe → AlertStore.checkLevels()

AlertStore (state: alerts)
  ├── getters → activeAlerts, criticalCount
  └── actions → addAlert(), dismissAlert()

Zadanie

Przeanalizuj działający system w edytorze. Zwróć uwagę na:

  1. ResourceStore - jak state, getters i actions współpracują
  2. AlertStore - jak jeden store reaguje na zmiany w drugim
  3. Komponent App - jak storeToRefs i actions są używane w template
  4. $subscribe - automatyczne tworzenie alertów przy niskim poziomie zasobów

Kluczowe wzorce:

  • Composition API style z ref() i computed()
  • Asynchroniczne actions z try/catch/finally
  • Store composition - resource store wywołuje alert store
  • storeToRefs do reaktywnej destrukturyzacji
  • $patch do grupowej aktualizacji state
Kod do tej lekcji: App.vue
<script setup>
import { ref, computed, watch } from 'vue'

// ===== ResourceStore =====
const resources = ref([
  { id: 'oxygen', name: 'Tlen', level: 85, max: 100, unit: '%', consumeRate: 2 },
  { id: 'water', name: 'Woda', level: 1200, max: 1500, unit: 'L', consumeRate: 30 },
  { id: 'energy', name: 'Energia', level: 72, max: 100, unit: '%', consumeRate: 5 }
])

// Gettery zasobów
const totalResourceHealth = computed(() => {
  const avg = resources.value.reduce((sum, r) => sum + (r.level / r.max * 100), 0)
  return Math.round(avg / resources.value.length)
})

const criticalResources = computed(() =>
  resources.value.filter(r => (r.level / r.max * 100) < 25)
)

const stationStatus = computed(() => {
  if (criticalResources.value.length > 0) return 'CRITICAL'
  if (totalResourceHealth.value < 50) return 'WARNING'
  return 'NOMINAL'
})

// Actions zasobów
function consumeResource(id) {
  const r = resources.value.find(res => res.id === id)
  if (r) {
    r.level = Math.max(0, r.level - r.consumeRate)
  }
}

function refillResource(id) {
  const r = resources.value.find(res => res.id === id)
  if (r) r.level = r.max
}

function consumeAll() {
  resources.value.forEach(r => {
    r.level = Math.max(0, r.level - r.consumeRate)
  })
}

function refillAll() {
  resources.value.forEach(r => r.level = r.max)
}

// ===== AlertStore =====
const alerts = ref([])

const activeAlerts = computed(() => alerts.value.filter(a => !a.dismissed))
const criticalAlertCount = computed(() => alerts.value.filter(a => a.type === 'critical' && !a.dismissed).length)

function addAlert(message, type = 'info') {
  alerts.value.push({
    id: Date.now() + Math.random(),
    message,
    type,
    time: new Date().toLocaleTimeString(),
    dismissed: false
  })
}

function dismissAlert(id) {
  const alert = alerts.value.find(a => a.id === id)
  if (alert) alert.dismissed = true
}

function clearAlerts() {
  alerts.value = []
}

// ===== Między stores: symulacja $subscribe =====
watch(resources, () => {
  resources.value.forEach(r => {
    const pct = (r.level / r.max) * 100
    if (pct < 10) {
      const exists = alerts.value.some(a =>
        a.message.includes(r.name) && a.type === 'critical' && !a.dismissed
      )
      if (!exists) addAlert(`${r.name} - STAN AWARYJNY: ${r.level}${r.unit}!`, 'critical')
    } else if (pct < 25) {
      const exists = alerts.value.some(a =>
        a.message.includes(r.name) && a.type === 'warning' && !a.dismissed
      )
      if (!exists) addAlert(`${r.name} - niski poziom: ${r.level}${r.unit}`, 'warning')
    }
  })
}, { deep: true })
</script>

<template>
  <div class="nova-lab">
    <h1>NOVA LAB - system zarządzania zasobami</h1>

    <div class="status-bar" :class="stationStatus.toLowerCase()">
      Status stacji: {{ stationStatus }} | Kondycja: {{ totalResourceHealth }}%
      <span v-if="criticalAlertCount"> | Alarmy: {{ criticalAlertCount }}</span>
    </div>

    <div class="main-grid">
      <div class="resources-section">
        <h2>Zasoby</h2>
        <div v-for="r in resources" :key="r.id" class="resource-card"
          :class="{ critical: (r.level/r.max*100) < 25, warning: (r.level/r.max*100) < 50 }">
          <div class="r-header">
            <strong>{{ r.name }}</strong>
            <span>{{ r.level }}/{{ r.max }} {{ r.unit }}</span>
          </div>
          <div class="r-bar">
            <div class="r-fill" :style="{ width: (r.level/r.max*100) + '%' }"></div>
          </div>
          <div class="r-btns">
            <button @click="consumeResource(r.id)" class="btn-sm">
              Zużyj (-{{ r.consumeRate }})
            </button>
            <button @click="refillResource(r.id)" class="btn-sm btn-green">Uzupełnij</button>
          </div>
        </div>
        <div class="global-btns">
          <button @click="consumeAll" class="btn">Zużyj wszystko</button>
          <button @click="refillAll" class="btn btn-green">Uzupełnij wszystko</button>
        </div>
      </div>

      <div class="alerts-section">
        <div class="alerts-header">
          <h2>System alarmów</h2>
          <button v-if="alerts.length" @click="clearAlerts" class="btn-sm">Wyczyść</button>
        </div>
        <div v-for="a in activeAlerts" :key="a.id" class="alert-item" :class="a.type">
          <div class="alert-content">
            <span class="alert-time">{{ a.time }}</span>
            <span>{{ a.message }}</span>
          </div>
          <button @click="dismissAlert(a.id)" class="dismiss">x</button>
        </div>
        <p v-if="!activeAlerts.length" class="empty">Wszystkie systemy w normie</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #00ff88;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 15px; text-align: center; }
h2 { color: #00b4d8; margin-bottom: 10px; }
.status-bar {
  text-align: center;
  padding: 10px;
  border: 2px solid;
  margin-bottom: 15px;
  font-weight: bold;
}
.status-bar.nominal { border-color: #00ff88; color: #00ff88; }
.status-bar.warning { border-color: #ff9900; color: #ff9900; }
.status-bar.critical { border-color: #ff4444; color: #ff4444; background: rgba(255,68,68,0.1); }
.main-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
.resources-section, .alerts-section {
  background: rgba(0, 180, 216, 0.1);
  border: 2px solid #00b4d8;
  padding: 15px;
}
.resource-card {
  border: 2px solid #00ff88;
  padding: 10px;
  margin-bottom: 8px;
}
.resource-card.warning { border-color: #ff9900; }
.resource-card.critical { border-color: #ff4444; background: rgba(255,68,68,0.05); }
.r-header { display: flex; justify-content: space-between; margin-bottom: 6px; }
.r-bar { height: 10px; background: #1a1e3f; border: 1px solid #00b4d8; }
.r-fill { height: 100%; background: #00ff88; transition: width 0.3s; }
.resource-card.warning .r-fill { background: #ff9900; }
.resource-card.critical .r-fill { background: #ff4444; }
.r-btns { display: flex; gap: 5px; margin-top: 6px; }
.btn-sm {
  background: #00b4d8;
  color: #0a0e27;
  border: none;
  padding: 3px 10px;
  cursor: pointer;
  font-family: monospace;
  font-size: 0.85em;
}
.btn-green { background: #00ff88; }
.global-btns { display: flex; gap: 8px; margin-top: 10px; }
.btn {
  background: #00b4d8;
  color: #0a0e27;
  border: none;
  padding: 6px 14px;
  cursor: pointer;
  font-family: monospace;
  flex: 1;
}
.btn:hover { background: #00ff88; }
.btn.btn-green { background: #00ff88; }
.alerts-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.alert-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  margin: 4px 0;
  border: 1px solid;
}
.alert-item.info { border-color: #00b4d8; }
.alert-item.warning { border-color: #ff9900; color: #ff9900; }
.alert-item.critical { border-color: #ff4444; color: #ff4444; }
.alert-time { color: #00b4d8; margin-right: 8px; font-size: 0.85em; }
.dismiss {
  background: none;
  border: 1px solid currentColor;
  color: inherit;
  cursor: pointer;
  padding: 1px 5px;
  font-family: monospace;
}
.empty { color: #666; font-style: italic; }
</style>

Widzisz błąd w tej lekcji?

Zadania praktyczne w grze

  • Edytor kodu

    Stwórz resource store z state, getters, actions, store composition i alertami.

  1. Zadanie z kodemPraktyka: Kompletny system zasobów
  2. Projekt do wysłaniaLink do mentora: Pinia Store
  3. WideoPodsumowanie modułu

Przydatne artykuły