← Back to Vue.js Course | Chapter 3: Reactivity | Lesson 2 of 7

Computed Properties का परिचय

एक computed property दूसरे data से derived एक value है जिसे Vue तब तक cache करता है जब तक कोई चीज़ जिस पर यह depend करती है न बदले।

In this page:

  1. Computed Properties
Syntax
markup
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

markup
<!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. #}
आम गलतियां
  1. expensive derived values के लिए methods इस्तेमाल करना
  2. computed के अंदर side effects cause करना
  3. एक 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:

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.