Computed Properties का परिचय
एक computed property दूसरे data से derived एक value है जिसे Vue तब तक cache करता है जब तक कोई चीज़ जिस पर यह depend करती है न बदले।
In this page:
Syntax
export default {
computed: {
computedName() {
return this.property * 2;
}
}
}
Computed Properties
Computed properties को ऐसे functions की तरह define करें जो reactive data पढ़ें और एक result return करें। Vue dependencies track करता है और सिर्फ तभी recalculate करता है जब ये बदलें, एक method के उलट, जो हर render पर चलता है। Writable computed properties get और set इस्तेमाल करते हैं।
Note:
Derived values के लिए computed इस्तेमाल करें और actions के लिए methods।
उदाहरण: Computed properties
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<p>{{ first }} {{ last }} => {{ fullName }}</p>
<p>Total: {{ total }}</p>
</div>
<script>
let runs = 0;
Vue.createApp({
data() { return { first: "Ada", last: "Lovelace", prices: [10, 20, 30] }; },
computed: {
fullName() { return this.first + " " + this.last; },
total() { runs++; return this.prices.reduce((a, b) => a + b, 0); },
},
}).mount("#app");
console.log("total getter executed once for 2 renders of the same value:", runs === 1);
</script>
</body>
</html>
<!-- Output:
Rendered: Ada Lovelace => Ada LovelaceTotal: 60
console: total getter executed once for 2 renders of the same value: true
-->
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. #}
आम गलतियां
- expensive derived values के लिए methods इस्तेमाल करना
- computed के अंदर side effects cause करना
- एक computed getter के अंदर data mutate करना
चैप्टर सारांश
- Computed values derived और cached हैं
- ये dependencies बदलने पर recompute करते हैं
- Methods हर call पर चलते हैं
- computed में side effects से बचें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: