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

Stores Define करना

defineStore एक unique id और इसके state, getters, और actions वाला एक store बनाता है।
Syntax
markup
import { defineStore } from 'pinia';

export const useStoreName = defineStore('store-id', {
  state: () => ({ property: value }),
  getters: {},
  actions: {}
});

Stores Define करना

defineStore("id", options) एक function return करता है जो आपको store instance देता है। Options form में state (एक function), getters, और actions हैं, Options API mirror करते हुए।

एक setup-style form ref, computed, और functions इस्तेमाल करता है और Composition API mirror करता है।

Note: Convention से returned function को useSomethingStore नाम दें।

उदाहरण: Defining stores

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>{{ user.name }} / {{ user.loggedIn }}</p></div>
<script>
  const useUserStore = Pinia.defineStore("user", {
    state: () => ({ name: "Guest", loggedIn: false }),
    getters: { label: (state) => state.name.toUpperCase() },
    actions: { login(name) { this.name = name; this.loggedIn = true; } },
  });
  const app = Vue.createApp({ setup() { return { user: useUserStore() }; } });
  app.use(Pinia.createPinia());
  app.mount("#app");
  console.log("store id:", useUserStore().$id, "| keys:", Object.keys(useUserStore().$state));
</script>
</body>
</html>

<!-- Output:
Rendered: Guest / false
console: store id: user | keys: name,loggedIn
-->
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. दो stores के लिए same id reuse करना
  2. state को एक function की बजाय एक object बनाना
  3. एक Pinia context के बाहर store call करना
चैप्टर सारांश
  • defineStore(id, options) से store बनता है
  • state एक function है
  • getters और actions supported हैं
  • इसे useXStore नाम दें
🔒

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.