Getters
Getters are computed properties of a store: values derived from state and cached.
In this page:
Syntax
getters: {
getterName: (state) => state.property * 2,
other() {
return this.getterName + 1;
}
}
Getters
Define getters as functions receiving state (or use this to access other getters). They are cached like computed properties and update when their dependencies change.
Getters can return functions to accept arguments, though that removes caching for those calls.
Note:
Use getters for filtered lists and totals instead of recomputing in components.
Example: Getters
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/[email protected]/lib/index.iife.js"></script>
<script src="https://unpkg.com/pinia@2/dist/pinia.iife.js"></script>
</head>
<body>
<div id="app"><p>Items: {{ cart.count }} | Total: ${{ cart.total }} | Expensive: {{ cart.expensive.length }}</p></div>
<script>
const useCart = Pinia.defineStore("cart", {
state: () => ({ items: [{ n: "pen", price: 3 }, { n: "lamp", price: 40 }, { n: "book", price: 12 }] }),
getters: {
count: (s) => s.items.length,
total: (s) => s.items.reduce((sum, i) => sum + i.price, 0),
expensive() { return this.items.filter((i) => i.price > 10); },
},
});
const app = Vue.createApp({ setup() { return { cart: useCart() }; } });
app.use(Pinia.createPinia());
app.mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: Items: 3 | Total: $55 | Expensive: 2
-->
Live Example
Related Topics
Common Mistakes
- Mutating state inside a getter
- Expecting a getter to accept arguments directly
- Using an arrow function when this is needed
Chapter Summary
- Getters are computed for stores
- They receive state
- Cached until dependencies change
- Return a function to take arguments
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: