Props नीचे, Events ऊपर
Golden rule: parents props से children को data भेजते हैं, और children events से वापस बात करते हैं।
In this page:
Syntax
// parent passes data down, child sends events up
<child-name :prop-name="value" @event-name="handler"></child-name>
Props Down Events Up
यह one-way data flow applications को predictable रखता है: state एक owner में रहती है और changes events के जरिए request होते हैं। एक child को कभी एक prop mutate नहीं करना चाहिए; इसकी बजाय यह एक event emit करता है और parent decide करता है कि इसकी अपनी state कैसे update करनी है।
Note:
अगर एक child को एक modifiable copy चाहिए, prop को local data में copy करें।
उदाहरण: Props down events up
<!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>Cart total: {{ total }}</p>
<product-row v-for="p in products" :key="p.id" :product="p" @buy="total += $event"></product-row>
</div>
<script>
const app = Vue.createApp({
data() { return { total: 0, products: [{ id: 1, name: "Pen", price: 3 }, { id: 2, name: "Book", price: 12 }] }; },
});
app.component("product-row", {
props: ["product"],
emits: ["buy"],
template: '<div>{{ product.name }} ${{ product.price }} <button @click="$emit(\'buy\', product.price)">Buy</button></div>',
});
app.mount("#app");
document.querySelectorAll("button")[1].click();
document.querySelectorAll("button")[1].click();
Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>
<!-- Output:
Rendered: Cart total: 24Pen $3 BuyBook $12 Buy
console: Cart total: 24
-->
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. #}
आम गलतियां
- child में एक prop mutate करना
- globals के जरिए state share करना
- हर जगह two-way binding
चैप्टर सारांश
- Props नीचे flow करते हैं
- Events ऊपर flow करते हैं
- Owner state update करता है
- कभी props mutate न करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: