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

Components में Stores का उपयोग

setup के अंदर store function call करें और इसकी state को एक normal reactive object की तरह पढ़ें या बदलें।
Syntax
markup
import { storeToRefs } from 'pinia';

setup() {
  const store = useStoreName();
  const { property } = storeToRefs(store);
  return { store, property };
}

Components में Stores Use करना

setup में useXStore() call करें और इसे return करें या state और getters के लिए reactivity रखने के लिए storeToRefs से destructure करें। Actions सीधे destructure हो सकते हैं। store.count++ जैसा direct mutation allowed है, और $patch कई changes batch करता है।

Note: state destructure करते वक्त storeToRefs इस्तेमाल करें, कभी plain destructuring नहीं।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. state destructure करना और reactivity खोना
  2. एक pinia के बिना setup के बाहर store call करना
  3. simple changes के लिए $patch overuse करना
चैप्टर सारांश
  • setup में store call करें
  • storeToRefs reactivity रखता है
  • Actions destructure हो सकते हैं
  • $patch updates batch करता है
🔒

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.