Kurs Vue.js · Moduł 11: Pinia

Getters w Pinia

2 min czytania ·
W tej lekcji4

Getters to wartości wyliczane na podstawie state - jak panele analityczne NOVA LAB, które przetwarzają surowe dane z czujników i prezentują je w czytelnej formie. Zmieniają się automatycznie gdy zmienia się state.

Podstawowe getters

W Composition API getters to zwykłe computed():

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useInventoryStore = defineStore('inventory', () => {
  const items = ref([
    { name: 'Oxygen Tank', quantity: 12, category: 'life-support' },
    { name: 'Water Filter', quantity: 5, category: 'life-support' },
    { name: 'Solar Panel', quantity: 8, category: 'energy' },
    { name: 'Drill Bit', quantity: 20, category: 'mining' }
  ])

  // Prosty getter
  const totalItems = computed(() =>
    items.value.reduce((sum, item) => sum + item.quantity, 0)
  )

  // Getter filtrujący
  const lifeSupportItems = computed(() =>
    items.value.filter(item => item.category === 'life-support')
  )

  // Getter sprawdzający warunek
  const hasShortage = computed(() =>
    items.value.some(item => item.quantity < 3)
  )

  return { items, totalItems, lifeSupportItems, hasShortage }
})

Getters używające innych getters

Getters mogą bazować na innych getters:

const lowStockItems = computed(() =>
  items.value.filter(item => item.quantity < 5)
)

const lowStockCount = computed(() => lowStockItems.value.length)

const stockStatus = computed(() => {
  if (lowStockCount.value === 0) return 'OK'
  if (lowStockCount.value <= 2) return 'WARNING'
  return 'CRITICAL'
})

Getters z parametrami

Computed nie przyjmuje argumentów, ale możesz zwrócić funkcję:

// Getter z parametrem - zwraca funkcję
const getItemsByCategory = computed(() => {
  return (category) =>
    items.value.filter(item => item.category === category)
})

const findItem = computed(() => {
  return (name) =>
    items.value.find(item =>
      item.name.toLowerCase().includes(name.toLowerCase())
    )
})

Użycie w komponencie:

<template>
  <div>
    <p>Total: {{ store.totalItems }}</p>
    <p>Status: {{ store.stockStatus }}</p>

    <!-- Getter z parametrem -->
    <div v-for="item in store.getItemsByCategory('energy')" :key="item.name">
      {{ item.name }}: {{ item.quantity }}
    </div>
  </div>
</template>

Getters w storeToRefs

Getters (computed) są częścią storeToRefs:

<script setup>
import { storeToRefs } from 'pinia'
import { useInventoryStore } from '@/stores/inventory'

const store = useInventoryStore()
const { items, totalItems, hasShortage } = storeToRefs(store)
</script>
Kod do tej lekcji: App.vue
<script setup>
import { ref, computed } from 'vue'

// Symulacja store magazynu z getterami
const items = ref([
  { name: 'Butla z tlenem', quantity: 12, category: 'life-support', unit: 'szt.' },
  { name: 'Filtr wody', quantity: 2, category: 'life-support', unit: 'szt.' },
  { name: 'Panel słoneczny', quantity: 8, category: 'energy', unit: 'szt.' },
  { name: 'Akumulator', quantity: 15, category: 'energy', unit: 'szt.' },
  { name: 'Wiertło', quantity: 20, category: 'mining', unit: 'szt.' },
  { name: 'Pojemnik na próbki skał', quantity: 1, category: 'mining', unit: 'szt.' }
])

const searchQuery = ref('')
const selectedCategory = ref('all')

// Getters
const totalItems = computed(() =>
  items.value.reduce((sum, item) => sum + item.quantity, 0)
)

const categories = computed(() =>
  ['all', ...new Set(items.value.map(i => i.category))]
)

const filteredItems = computed(() => {
  let result = items.value
  if (selectedCategory.value !== 'all') {
    result = result.filter(i => i.category === selectedCategory.value)
  }
  if (searchQuery.value) {
    const q = searchQuery.value.toLowerCase()
    result = result.filter(i => i.name.toLowerCase().includes(q))
  }
  return result
})

const lowStockItems = computed(() =>
  items.value.filter(item => item.quantity < 5)
)

const stockStatus = computed(() => {
  if (lowStockItems.value.length === 0) return 'OK'
  if (lowStockItems.value.length <= 2) return 'WARNING'
  return 'CRITICAL'
})

// Getter z parametrem
const getByCategory = computed(() => {
  return (cat) => items.value.filter(i => i.category === cat)
})
</script>

<template>
  <div class="nova-lab">
    <h1>NOVA LAB - gettery magazynu</h1>

    <div class="stats-bar">
      <div class="stat-card">
        <div class="stat-value">{{ totalItems }}</div>
        <div class="stat-label">Sztuk łącznie</div>
      </div>
      <div class="stat-card">
        <div class="stat-value" :class="stockStatus.toLowerCase()">{{ stockStatus }}</div>
        <div class="stat-label">Stan magazynu</div>
      </div>
      <div class="stat-card">
        <div class="stat-value warning">{{ lowStockItems.length }}</div>
        <div class="stat-label">Niski stan</div>
      </div>
    </div>

    <div class="controls">
      <input v-model="searchQuery" placeholder="Szukaj..." class="search-input" />
      <select v-model="selectedCategory" class="select">
        <option v-for="cat in categories" :key="cat" :value="cat">
          {{ cat === 'all' ? 'Wszystkie kategorie' : cat }}
        </option>
      </select>
    </div>

    <div class="inventory-grid">
      <div v-for="item in filteredItems" :key="item.name"
        class="item-card" :class="{ 'low-stock': item.quantity < 5 }">
        <div class="item-name">{{ item.name }}</div>
        <div class="item-qty">{{ item.quantity }} {{ item.unit }}</div>
        <div class="item-cat">{{ item.category }}</div>
      </div>
    </div>

    <div v-if="lowStockItems.length" class="alert-box">
      Niski stan: {{ lowStockItems.map(i => i.name).join(', ') }}
    </div>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #00ff88;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 20px; text-align: center; }
.stats-bar { display: flex; gap: 10px; margin-bottom: 15px; justify-content: center; }
.stat-card {
  background: rgba(0, 180, 216, 0.1);
  border: 2px solid #00b4d8;
  padding: 12px 20px;
  text-align: center;
}
.stat-value { font-size: 1.4em; font-weight: bold; }
.stat-label { color: #00b4d8; font-size: 0.8em; margin-top: 4px; }
.ok { color: #00ff88; }
.warning { color: #ff9900; }
.critical { color: #ff4444; }
.controls { display: flex; gap: 10px; margin-bottom: 15px; max-width: 500px; margin: 0 auto 15px; }
.search-input, .select {
  background: #0a0e27;
  border: 2px solid #00b4d8;
  color: #00ff88;
  padding: 8px;
  font-family: monospace;
  flex: 1;
}
.inventory-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 10px; }
.item-card {
  background: rgba(0, 255, 136, 0.05);
  border: 2px solid #00ff88;
  padding: 12px;
}
.item-card.low-stock { border-color: #ff4444; background: rgba(255, 68, 68, 0.1); }
.item-name { font-weight: bold; margin-bottom: 5px; }
.item-qty { color: #00b4d8; }
.item-cat { color: #666; font-size: 0.85em; margin-top: 4px; }
.alert-box {
  margin-top: 15px;
  padding: 10px;
  background: rgba(255, 68, 68, 0.1);
  border: 2px solid #ff4444;
  color: #ff4444;
}
</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. 1. Czym są getters w Pinia (Composition API)?

  2. 2. Jak zdefiniować getter w Composition API style?

To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.

Zadania praktyczne w grze

  • Edytor kodu

    Stwórz gettery: totalItems, hasShortage i stockStatus.

  • Układanie w poziomie

    Ułóż definicję gettera computed w store:

  • Klikanie w kolejności

    Ułóż getter z parametrem (zwracający funkcję):

  • Edytor kodu

    Zdefiniuj lifeSupportItems (filtrujący) i getItemsByCategory (parametryczny getter).

  1. PytanieCzym są getters?
  2. PytanieGetters w Composition API
  3. Zadanie z kodemPraktyka: Getters
  4. Ułóż w kolejnościDefinicja gettera
  5. PytanieGetter z parametrem
  6. Kliknij w kolejnościGetter parametryczny
  7. Zadanie z kodemPraktyka: Filtrujące gettery

Przydatne artykuły