Kurs Vue.js · Moduł 11: Pinia
Kompozycja Stores
W tej lekcji3
W NOVA LAB różne systemy stacji muszą ze sobą współpracować - system tlenu komunikuje się z systemem alarmowym, a system nawigacji z systemem komunikacji. Podobnie w Pinia - stores mogą importować i używać innych stores.
Store używający innego store
// stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useAuthStore = defineStore('auth', () => {
const user = ref(null)
const token = ref(null)
const isAuthenticated = computed(() => !!token.value)
const userName = computed(() => user.value?.name || 'Guest')
async function login(credentials) {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials)
})
const data = await res.json()
token.value = data.token
user.value = data.user
}
function logout() {
user.value = null
token.value = null
}
return { user, token, isAuthenticated, userName, login, logout }
})// stores/missions.js - używa auth store
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useAuthStore } from './auth'
export const useMissionsStore = defineStore('missions', () => {
const missions = ref([])
async function fetchMissions() {
// Użyj auth store do pobrania tokena
const authStore = useAuthStore()
if (!authStore.isAuthenticated) {
throw new Error('Must be logged in')
}
const res = await fetch('/api/missions', {
headers: {
'Authorization': `Bearer ${authStore.token}`
}
})
missions.value = await res.json()
}
return { missions, fetchMissions }
})Wzajemne zależności stores
Stores mogą nawzajem się używać, ale wywołuj useStore() wewnątrz actions (nie na górze setup function), aby uniknąć problemów z cyklicznymi zależnościami:
// stores/notifications.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useNotificationStore = defineStore('notifications', () => {
const notifications = ref([])
function add(message, type = 'info') {
notifications.value.push({
id: Date.now(),
message,
type,
timestamp: new Date()
})
}
function remove(id) {
notifications.value = notifications.value.filter(n => n.id !== id)
}
return { notifications, add, remove }
})
// stores/resources.js - używa notifications
import { useNotificationStore } from './notifications'
export const useResourceStore = defineStore('resources', () => {
const oxygen = ref(100)
function consumeOxygen(amount) {
oxygen.value -= amount
if (oxygen.value < 20) {
// Wywołaj useStore WEWNĄTRZ action
const notifStore = useNotificationStore()
notifStore.add('Oxygen level critical!', 'danger')
}
}
return { oxygen, consumeOxygen }
})Architektura wielu stores
Zaleca się tworzenie wielu małych, specjalizowanych stores zamiast jednego dużego:
stores/
├── auth.js # Autoryzacja użytkownika
├── resources.js # Zasoby stacji (tlen, woda, energia)
├── crew.js # Dane załogi
├── missions.js # Misje i zadania
├── notifications.js # System powiadomień
└── settings.js # Ustawienia aplikacjiKażdy store odpowiada za jeden "moduł" aplikacji - tak jak każdy moduł stacji NOVA LAB ma swoją funkcję.
Kod do tej lekcji: App.vue
<script setup>
import { ref, computed } from 'vue'
// Kompozycja stores - AuthStore
const user = ref({ name: 'Komandor Nova', role: 'admin' })
const token = ref('jwt-token-xyz')
const isAuthenticated = computed(() => !!token.value)
// Kompozycja stores - ResourceStore (korzysta z AuthStore)
const resources = ref([
{ id: 1, name: 'Tlen', level: 92, unit: '%' },
{ id: 2, name: 'Woda', level: 78, unit: '%' },
{ id: 3, name: 'Energia', level: 65, unit: '%' }
])
// Kompozycja stores - NotificationStore
const notifications = ref([])
function addNotification(message, type = 'info') {
const id = Date.now()
notifications.value.push({ id, message, type, time: new Date().toLocaleTimeString() })
setTimeout(() => {
notifications.value = notifications.value.filter(n => n.id !== id)
}, 4000)
}
// Actions z ResourceStore korzystają z NotificationStore
function consumeResource(id, amount) {
const resource = resources.value.find(r => r.id === id)
if (!resource) return
resource.level = Math.max(0, resource.level - amount)
if (resource.level < 20) {
// Między stores: zasoby -> powiadomienia
addNotification(`${resource.name} - krytycznie niski poziom: ${resource.level}${resource.unit}!`, 'danger')
} else if (resource.level < 50) {
addNotification(`${resource.name} poniżej 50%: ${resource.level}${resource.unit}`, 'warning')
}
}
function refillResource(id) {
const resource = resources.value.find(r => r.id === id)
if (resource) {
resource.level = 100
addNotification(`${resource.name}: uzupełniono do 100%`, 'success')
}
}
// Getter łączący stores
const criticalResources = computed(() =>
resources.value.filter(r => r.level < 30)
)
</script>
<template>
<div class="nova-lab">
<h1>NOVA LAB - kompozycja stores</h1>
<div class="user-bar" v-if="isAuthenticated">
Zalogowano: {{ user.name }} ({{ user.role }})
</div>
<div class="resources-grid">
<div v-for="r in resources" :key="r.id"
class="resource-card" :class="{ critical: r.level < 20, warning: r.level < 50 }">
<h3>{{ r.name }}</h3>
<div class="level-bar">
<div class="level-fill" :style="{ width: r.level + '%' }"></div>
</div>
<div class="level-text">{{ r.level }}{{ r.unit }}</div>
<div class="r-actions">
<button @click="consumeResource(r.id, 15)" class="btn">-15</button>
<button @click="refillResource(r.id)" class="btn btn-green">Uzupełnij</button>
</div>
</div>
</div>
<div v-if="criticalResources.length" class="critical-alert">
KRYTYCZNE: {{ criticalResources.map(r => r.name).join(', ') }}
</div>
<div class="notifications">
<div v-for="n in notifications" :key="n.id" class="notif" :class="n.type">
{{ n.time }} - {{ n.message }}
</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; }
.user-bar {
text-align: center;
padding: 8px;
background: rgba(0, 180, 216, 0.1);
border: 1px solid #00b4d8;
margin-bottom: 15px;
color: #00b4d8;
}
.resources-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 15px; }
.resource-card {
background: rgba(0, 255, 136, 0.05);
border: 2px solid #00ff88;
padding: 15px;
text-align: center;
}
.resource-card.warning { border-color: #ff9900; }
.resource-card.critical { border-color: #ff4444; background: rgba(255, 68, 68, 0.1); }
h3 { color: #00b4d8; margin-bottom: 8px; }
.level-bar { height: 12px; background: #1a1e3f; border: 1px solid #00b4d8; margin: 8px 0; }
.level-fill { height: 100%; background: #00ff88; transition: width 0.3s; }
.resource-card.warning .level-fill { background: #ff9900; }
.resource-card.critical .level-fill { background: #ff4444; }
.level-text { font-size: 1.2em; font-weight: bold; margin-bottom: 8px; }
.r-actions { display: flex; gap: 5px; justify-content: center; }
.btn {
background: #00b4d8;
color: #0a0e27;
border: none;
padding: 5px 12px;
cursor: pointer;
font-family: monospace;
}
.btn-green { background: #00ff88; }
.critical-alert {
padding: 10px;
background: rgba(255, 68, 68, 0.2);
border: 2px solid #ff4444;
color: #ff4444;
text-align: center;
margin-bottom: 15px;
font-weight: bold;
}
.notifications { max-width: 500px; margin: 0 auto; }
.notif {
padding: 8px;
margin: 4px 0;
border: 1px solid;
font-size: 0.9em;
}
.notif.info { border-color: #00b4d8; color: #00b4d8; }
.notif.warning { border-color: #ff9900; color: #ff9900; }
.notif.danger { border-color: #ff4444; color: #ff4444; }
.notif.success { border-color: #00ff88; color: #00ff88; }
</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. Czy store w Pinia może importować i używać innego store?
2. Gdzie najlepiej wywoływać useStore() drugiego store wewnątrz store?
To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.
Zadania praktyczne w grze
- Edytor kodu
Stwórz tasks store używający auth store - fetchTasks sprawdza isAuthenticated.
- Układanie w pionie
Uporządkuj stores od najbardziej niezależnego do najbardziej zależnego:
- Klikanie w kolejności
Ułóż kod action wywołującej inny store:
- Edytor kodu
Stwórz resource store z alertami - consume generuje alerty przy niskim poziomie.