Derived Store Getters
Part of the Routing and State section of Coddy's Vue journey. Lesson 32 of 55.
A getter derives a value from store state. It is the store equivalent of a computed value: components consume the result while Pinia tracks the state it depends on. Keeping a total derived avoids synchronization bugs between source fields and a copied result.
export const useBasketStore=defineStore('basket',{
state:()=>({count:3,unitPrice:6}),
getters:{cost:state=>state.count*state.unitPrice}
});Read a getter as a property, such as basket.cost. Changing either input updates the derived result. Getters should compute results without mutating state; put changes in actions or explicit state updates.
Challenge
MediumAdd a getter total to the supplied options store that derives boxes * price. Show it in p#total. Keep quantity and price as state rather than maintaining a second manually synchronized total. Button #price increases price by one; existing Add and Remove change boxes, stopping at zero.
Keep the supplied route readout and bootstrap files.
Try it yourself
<!doctype html><html><head><meta charset="UTF-8"><title>Routing practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Routing and State
4Query State
Reading Query ValuesCommitting Search QueriesPreserving Other FiltersNormalizing Query NumbersRecap: Catalog Filters7Pinia Options Stores
Shared Store StateDerived Store GettersStore Actions and BoundsExtracting Reactive FieldsRecap: Seat Counter2Navigation Actions
Navigation from HandlersReplacing HistoryHistory TravelCurrent Navigation LinksRecap: Save and Review5Nested Layouts
Parent and Child OutletsDefault Child ViewsRelative Child PathsAncestor Navigation StateRecap: Library Workspace8Store Design
Setup Store StructurePatching Related StateResetting Store StateComposing Related StoresRecap: Trip Pack11Workshop Planner Project
Planner RoutesShared Reservations