data() Function का परिचय
data function हर component instance के लिए state का एक fresh object return करता है।
In this page:
Syntax
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
<!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. #}
आम गलतियां
- components में data को एक plain object बनाना
- बाद में नई properties add करना और reactivity की उम्मीद करना
- 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: