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

data() Function का परिचय

data function हर component instance के लिए state का एक fresh object return करता है।

In this page:

  1. data() Function
Syntax
markup
export default {
  data() {
    return {
      property: value
    };
  }
}

data() Function

Options API में, data एक function होना चाहिए जो एक object return करे ताकि हर component instance को इसकी अपनी copy मिले। Return हुई properties reactive बन जाती हैं और this पर accessible होती हैं।

बाद में add हुई properties तब तक reactive नहीं होतीं जब तक पहले से declare न हों, इसलिए जो भी field आपको चाहिए वह declare करें।

Note: data में सारे state fields declare करें, भले ही empty हों, ताकि वे reactive हों।

उदाहरण: data() function

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">
  <counter-box></counter-box>
  <counter-box></counter-box>
</div>
<script>
  const app = Vue.createApp({});
  app.component("counter-box", {
    data() { return { n: 0 }; },
    template: '<button @click="n++">clicks: {{ n }}</button>',
  });
  app.mount("#app");
  const [a, b] = document.querySelectorAll("button");
  a.click(); a.click(); b.click();
  Vue.nextTick(() => console.log("independent state:", a.textContent, "|", b.textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: clicks: 2clicks: 1
console: independent state: clicks: 2 | clicks: 1
-->
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. components में data को एक plain object बनाना
  2. बाद में नई properties add करना और reactivity की उम्मीद करना
  3. Arrow functions इस्तेमाल करना जो this तोड़ देते हैं
चैप्टर सारांश
  • data एक object return करता है
  • हर instance को इसकी अपनी state मिलती है
  • सारे fields पहले से declare करें
  • Properties this पर appear होती हैं
🔒

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.