← Back to Vue.js Course | Chapter 6: Component Communication | Lesson 5 of 7

Event Bus का परिचय

एक event bus एक shared emitter है जो unrelated components एक-दूसरे को messages भेजने के लिए इस्तेमाल करते हैं।

In this page:

  1. Event Bus

Event Bus

Vue 3 ने $on, $off, और $once हटा दिए, इसलिए एक event bus अब mitt जैसे एक छोटे emitter या एक hand-written एक से बनता है। यह components decouple करता है लेकिन data flow trace करना मुश्किल बनाता है, इसलिए shared state के लिए state management या provide/inject आमतौर पर बेहतर choice है।

Note: Vue 3 अब कोई event bus ship नहीं करता; mitt या एक store इस्तेमाल करें।

उदाहरण: Event bus

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">
  <sender-btn></sender-btn>
  <receiver-box></receiver-box>
</div>
<script>
  const bus = { handlers: {}, on(e, f) { (this.handlers[e] ||= []).push(f); }, emit(e, d) { (this.handlers[e] || []).forEach((f) => f(d)); } };
  const app = Vue.createApp({});
  app.component("sender-btn", { template: '<button @click="send">Send</button>', methods: { send() { bus.emit("msg", "hello bus"); } } });
  app.component("receiver-box", {
    data() { return { last: "nothing yet" }; },
    created() { bus.on("msg", (m) => (this.last = m)); },
    template: "<p>Received: {{ last }}</p>",
  });
  app.mount("#app");
  document.querySelector("button").click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: SendReceived: hello bus
console: Received: hello bus
-->
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. Vue 3 में this.$on इस्तेमाल करना
  2. unmounted में unsubscribe करना भूल जाना
  3. events पर app-wide state बनाना
चैप्टर सारांश
  • Vue 3 ने $on और $off हटा दिए
  • mitt जैसा एक tiny emitter इस्तेमाल करें
  • unmount करते वक्त unsubscribe करें
  • Shared state के लिए stores prefer करें
🔒

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.