← Back to Vue.js Course | Chapter 4: Components | Lesson 3 of 7

Custom Events ($emit) का परिचय

Children एक custom event emit करके अपने parent को बताते हैं कि कुछ हुआ।

In this page:

  1. Custom Events ($emit)
Syntax
markup
// child
this.$emit('event-name', payload);

// parent template
<child-name @event-name="handler"></child-name>

Custom Events ($emit)

एक child this.$emit("event-name", payload) call करता है, और parent @event-name से सुनता है। Clarity और validation के लिए emits option में emitted events declare करें। यह props से नीचे और events से ऊपर data flow बनाए रखता है।

Note: templates में सुनते वक्त events को kebab-case में name करें।

उदाहरण: Custom events ($emit)

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>Parent total: {{ total }}</p>
  <add-button :amount="5" @added="total += $event"></add-button>
</div>
<script>
  const app = Vue.createApp({ data() { return { total: 0 }; } });
  app.component("add-button", {
    props: ["amount"],
    emits: ["added"],
    template: '<button @click="$emit(\'added\', amount)">Add {{ amount }}</button>',
  });
  app.mount("#app");
  const b = document.querySelector("button");
  b.click(); b.click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: Parent total: 10Add 5
console: Parent total: 10
-->
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. emits declare करना भूल जाना
  2. child से directly parent state बदलना
  3. emit और listener के बीच naming mismatches
चैप्टर सारांश
  • $emit ऊपर की ओर एक event भेजता है
  • Parent @ से सुनता है
  • emits में events declare करें
  • Payload arguments की तरह pass होता है
🔒

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.