Using stores in components
Call the store function inside setup and read or change its state like a normal reactive object.
In this page:
Syntax
import { storeToRefs } from 'pinia';
setup() {
const store = useStoreName();
const { property } = storeToRefs(store);
return { store, property };
}
Using stores in components
Call useXStore() in setup and return it or destructure with storeToRefs to keep reactivity for state and getters. Actions can be destructured directly. Direct mutation such as store.count++ is allowed, and $patch batches several changes.
Note:
Use storeToRefs when destructuring state, never plain destructuring.
Example: Using stores in components
<!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>{{ count }} doubled is {{ double }}</p>
<button @click="increment">+1</button>
</div>
<script>
const useCounter = Pinia.defineStore("counter", {
state: () => ({ count: 1 }),
getters: { double: (s) => s.count * 2 },
actions: { increment() { this.count++; } },
});
const app = Vue.createApp({
setup() {
const store = useCounter();
const { count, double } = Pinia.storeToRefs(store);
return { count, double, increment: store.increment };
},
});
app.use(Pinia.createPinia());
app.mount("#app");
document.querySelector("button").click();
Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>
<!-- Output:
Rendered: 2 doubled is 4+1
console: 2 doubled is 4
-->
Live Example
Related Topics
Common Mistakes
- Destructuring state and losing reactivity
- Calling the store outside setup without a pinia
- Overusing $patch for simple changes
Chapter Summary
- Call the store in setup
- storeToRefs keeps reactivity
- Actions can be destructured
- $patch batches updates
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: