Getters का परिचय
Getters एक store की computed properties हैं: state से derived और cached values।
In this page:
Syntax
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
<!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. #}
आम गलतियां
- एक getter के अंदर state mutate करना
- यह उम्मीद करना कि एक getter सीधे arguments accept करेगा
- जब 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: