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

Getters का परिचय

Getters एक store की computed properties हैं: state से derived और cached values।

In this page:

  1. Getters
Syntax
markup
getters: {
  getterName: (state) => state.property * 2,
  other() {
    return this.getterName + 1;
  }
}

Getters

Getters को state receive करने वाले functions की तरह define करें (या दूसरे getters access करने के लिए this इस्तेमाल करें)। ये computed properties की तरह cached हैं और इनकी dependencies बदलने पर update होते हैं।

Getters arguments accept करने के लिए functions return कर सकते हैं, हालाँकि यह उन calls के लिए caching हटा देता है।

Note: Components में recompute करने की बजाय filtered lists और totals के लिए getters इस्तेमाल करें।

उदाहरण: Getters

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>Items: {{ cart.count }} | Total: ${{ cart.total }} | Expensive: {{ cart.expensive.length }}</p></div>
<script>
  const useCart = Pinia.defineStore("cart", {
    state: () => ({ items: [{ n: "pen", price: 3 }, { n: "lamp", price: 40 }, { n: "book", price: 12 }] }),
    getters: {
      count: (s) => s.items.length,
      total: (s) => s.items.reduce((sum, i) => sum + i.price, 0),
      expensive() { return this.items.filter((i) => i.price > 10); },
    },
  });
  const app = Vue.createApp({ setup() { return { cart: useCart() }; } });
  app.use(Pinia.createPinia());
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Items: 3 | Total: $55 | Expensive: 2
-->
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. एक getter के अंदर state mutate करना
  2. यह उम्मीद करना कि एक getter सीधे arguments accept करेगा
  3. जब this चाहिए हो एक arrow function इस्तेमाल करना
चैप्टर सारांश
  • Getters stores के लिए computed हैं
  • ये state receive करते हैं
  • Dependencies बदलने तक cached
  • Arguments लेने के लिए एक function return करें
🔒

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.