We use cookies to enhance your experience on the site
CodeWorlds

Getters in Pinia

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()
:

1import { defineStore } from 'pinia'
2import { ref, computed } from 'vue'
3
4export const useInventoryStore = defineStore('inventory', () => {
5  const items = ref([
6    { name: 'Oxygen Tank', quantity: 12, category: 'life-support' },
7    { name: 'Water Filter', quantity: 5, category: 'life-support' },
8    { name: 'Solar Panel', quantity: 8, category: 'energy' },
9    { name: 'Drill Bit', quantity: 20, category: 'mining' }
10  ])
11
12  // Simple getter
13  const totalItems = computed(() =>
14    items.value.reduce((sum, item) => sum + item.quantity, 0)
15  )
16
17  // Filtering getter
18  const lifeSupportItems = computed(() =>
19    items.value.filter(item => item.category === 'life-support')
20  )
21
22  // Condition-checking getter
23  const hasShortage = computed(() =>
24    items.value.some(item => item.quantity < 3)
25  )
26
27  return { items, totalItems, lifeSupportItems, hasShortage }
28})

Getters Using Other Getters

Getters can be based on other getters:

1const lowStockItems = computed(() =>
2  items.value.filter(item => item.quantity < 5)
3)
4
5const lowStockCount = computed(() => lowStockItems.value.length)
6
7const stockStatus = computed(() => {
8  if (lowStockCount.value === 0) return 'OK'
9  if (lowStockCount.value <= 2) return 'WARNING'
10  return 'CRITICAL'
11})

Getters with Parameters

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

1// Getter with parameter - returns a function
2const getItemsByCategory = computed(() => {
3  return (category) =>
4    items.value.filter(item => item.category === category)
5})
6
7const findItem = computed(() => {
8  return (name) =>
9    items.value.find(item =>
10      item.name.toLowerCase().includes(name.toLowerCase())
11    )
12})

Usage in a component:

1<template>
2  <div>
3    <p>Total: {{ store.totalItems }}</p>
4    <p>Status: {{ store.stockStatus }}</p>
5
6    <!-- Getter with parameter -->
7    <div v-for="item in store.getItemsByCategory('energy')" :key="item.name">
8      {{ item.name }}: {{ item.quantity }}
9    </div>
10  </div>
11</template>

Getters in storeToRefs

Getters (computed) are part of

storeToRefs
:

1<script setup>
2import { storeToRefs } from 'pinia'
3import { useInventoryStore } from '@/stores/inventory'
4
5const store = useInventoryStore()
6const { items, totalItems, hasShortage } = storeToRefs(store)
7</script>
Go to CodeWorlds