Shared Store State
Part of the Routing and State section of Coddy's Vue journey. Lesson 31 of 55.
Pinia gives components a shared store within an installed Pinia instance. Define a store with a unique id and a state factory, then call its useStore function where the application needs that state. Two callers receive the same store rather than two independent local refs.
export const useBasketStore=defineStore('basket',{
state:()=>({items:1})
});
// In a component after app.use(createPinia()):
const basket=useBasketStore();The bootstrap installs Pinia before mounting. Store properties are reactive and are accessed directly as basket.items, without .value on the store object. Use local refs for private drafts and a store for state that genuinely belongs across components or routes.
Challenge
MediumCreate the options store useSupplyStore with unique id supplies. Its state factory returns boxes: 2 and price: 4. The supplied controls add or remove one box, stopping at zero. Both the editor count p#boxes and the separate Summary component count p#summary must reflect the same store instance.
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