Vue.js course ยท Module 11: Pinia

Getters in Pinia

2 min read ยท
In this lesson4

Getters are values computed based on state - like NOVA LAB analytical panels that process raw sensor data and present it in a readable form. They change automatically when the state changes.

Basic Getters

In Composition API, getters are simply 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' }
  ])

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

  // Filtering getter
  const lifeSupportItems = computed(() =>
    items.value.filter(item => item.category === 'life-support')
  )

  // Condition-checking getter
  const hasShortage = computed(() =>
    items.value.some(item => item.quantity < 3)
  )

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

Getters Using Other Getters

Getters can be based on other 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 with Parameters

Computed doesn't accept arguments, but you can return a function:

// Getter with parameter - returns a function
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())
    )
})

Usage in a component:

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

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

Getters in storeToRefs

Getters (computed) are part of storeToRefs:

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

const store = useInventoryStore()
const { items, totalItems, hasShortage } = storeToRefs(store)
</script>
Code for this lesson: App.vue
<script setup>
import { ref, computed } from 'vue'

// Inventory Store simulation with getters
const items = ref([
  { name: 'Oxygen Tank', quantity: 12, category: 'life-support', unit: 'units' },
  { name: 'Water Filter', quantity: 2, category: 'life-support', unit: 'units' },
  { name: 'Solar Panel', quantity: 8, category: 'energy', unit: 'units' },
  { name: 'Battery Pack', quantity: 15, category: 'energy', unit: 'units' },
  { name: 'Drill Bit', quantity: 20, category: 'mining', unit: 'pcs' },
  { name: 'Rock Sample Container', quantity: 1, category: 'mining', unit: 'units' }
])

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 with a parameter
const getByCategory = computed(() => {
  return (cat) => items.value.filter(i => i.category === cat)
})
</script>

<template>
  <div class="nova-lab">
    <h1>NOVA LAB - Inventory Getters</h1>

    <div class="stats-bar">
      <div class="stat-card">
        <div class="stat-value">{{ totalItems }}</div>
        <div class="stat-label">Total Items</div>
      </div>
      <div class="stat-card">
        <div class="stat-value" :class="stockStatus.toLowerCase()">{{ stockStatus }}</div>
        <div class="stat-label">Stock Status</div>
      </div>
      <div class="stat-card">
        <div class="stat-value warning">{{ lowStockItems.length }}</div>
        <div class="stat-label">Low Stock</div>
      </div>
    </div>

    <div class="controls">
      <input v-model="searchQuery" placeholder="Search..." class="search-input" />
      <select v-model="selectedCategory" class="select">
        <option v-for="cat in categories" :key="cat" :value="cat">
          {{ cat === 'all' ? 'All Categories' : 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">
      Low stock: {{ 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>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What are getters in Pinia?

  2. 2. How are getters defined in a Composition API store?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create the getters totalItems, hasShortage and stockStatus.

  • Horizontal ordering

    Arrange the elements to define a getter in a Pinia store

  • Click in order

    Arrange the elements to create a getter with a parameter

  • Code editor

    Define lifeSupportItems (filtering) and getItemsByCategory (a parameterized getter).

  1. QuestionWhat Are Getters?
  2. QuestionGetters in Composition API
  3. Coding taskPractice: Getters
  4. Put in orderGetter Definition
  5. QuestionGetter with Parameter
  6. Click in orderParameterized Getter
  7. Coding taskPractice: Filtering Getters

Useful articles