← Back to Vue.js Course | Chapter 8: State Management | Lesson 4 of 6

Using stores in components

Call the store function inside setup and read or change its state like a normal reactive object.
Syntax
markup
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

markup
<!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
  1. Destructuring state and losing reactivity
  2. Calling the store outside setup without a pinia
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.