Table of Contents
What is an event bus?
Create event bus
Implementing component communication through the event bus
Subscribing events
Trigger events
Sample Application
Home Web Front-end Vue.js How to implement communication between components through event bus in Vue

How to implement communication between components through event bus in Vue

Oct 15, 2023 am 08:30 AM
vue communication event bus

How to implement communication between components through event bus in Vue

How to implement communication between components through the event bus in Vue requires specific code examples

The event bus is a common component communication mechanism in Vue, which allows Concise and flexible communication between different components without explicitly introducing parent-child component relationships or using state management libraries such as Vuex. This article will introduce how to implement communication between components through the event bus in Vue, and provide specific code examples.

What is an event bus?

The event bus is a mechanism for passing messages between components. In Vue, we can use a Vue instance to create an event bus through which communication between components is achieved. The event bus allows multiple components to subscribe to and trigger the same event, thereby achieving decoupling and flexible communication between components.

Create event bus

Creating an event bus in Vue is very simple. We can mount an empty Vue instance as an event bus on an independent Vue instance. The following is a sample code to create an event bus:

// EventBus.js

import Vue from 'vue';
export default new Vue();
Copy after login

In the above sample code, we exported a Vue instance, which is our event bus. In other components, we can introduce the event bus instance through the import statement.

Implementing component communication through the event bus

There are two main steps to achieve communication between components through the event bus: subscribing to events and triggering events.

Subscribing events

In components that need to receive messages, we can use the $on method to subscribe to specific events. Here is an example:

// ComponentA.vue

import EventBus from './EventBus.js';

export default {
  created() {
    EventBus.$on('custom-event', this.handleEvent);
  },
  destroyed() {
    EventBus.$off('custom-event', this.handleEvent);
  },
  methods: {
    handleEvent(payload) {
      console.log(`Received message: ${payload}`);
    }
  }
}
Copy after login

In the above example, we subscribed to a named custom-event using the $on method inside the created lifecycle hook event and pass in the event handler function handleEvent. When custom-event is triggered, the handleEvent function will be called and receive the passed data.

Trigger events

In components that need to send messages, we can use the $emit method to trigger specific events. Here is an example:

// ComponentB.vue

import EventBus from './EventBus.js';

export default {
  methods: {
    sendMessage() {
      EventBus.$emit('custom-event', 'Hello, EventBus!');
    }
  }
}
Copy after login

In the above example, we used the $emit method in the sendMessage method to trigger an event named custom-event event, and passed the string 'Hello, EventBus!' as data.

Sample Application

The following is a simple sample application that demonstrates how to use the event bus to achieve communication between two components.

// ParentComponent.vue

<template>
  <div>
    <child-component></child-component>
  </div>
</template>

<script>
import EventBus from './EventBus.js';
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  mounted() {
    EventBus.$on('message', this.handleMessage);
  },
  destroyed() {
    EventBus.$off('message', this.handleMessage);
  },
  methods: {
    handleMessage(payload) {
      console.log(`Received message: ${payload}`);
    }
  }
}
</script>


// ChildComponent.vue

<template>
  <div>
    <button @click="sendMessage">Send Message</button>
  </div>
</template>

<script>
import EventBus from './EventBus.js';

export default {
  methods: {
    sendMessage() {
      EventBus.$emit('message', 'Hello, EventBus!');
    }
  }
}
</script>
Copy after login

In the above example, ParentComponent is the parent component and ChildComponent is the child component. When a button in ChildComponent is clicked, it sends a message through the event bus, and ParentComponent subscribes to the event and receives the message printed to the console.

Through the event bus, we can achieve decoupling and flexible communication between different components. No matter how complex the relationship between components is, communication between components can be easily achieved using the event bus. Of course, in some larger-scale applications, we can also consider using state management libraries such as Vuex to manage communication and shared state between components.

To summarize, this article introduces the concept and usage of the event bus, and provides specific code examples. I hope this article can help you better understand and use the event bus mechanism in Vue.

The above is the detailed content of How to implement communication between components through event bus in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use echarts in vue How to use echarts in vue May 09, 2024 pm 04:24 PM

Using ECharts in Vue makes it easy to add data visualization capabilities to your application. Specific steps include: installing ECharts and Vue ECharts packages, introducing ECharts, creating chart components, configuring options, using chart components, making charts responsive to Vue data, adding interactive features, and using advanced usage.

The role of export default in vue The role of export default in vue May 09, 2024 pm 06:48 PM

Question: What is the role of export default in Vue? Detailed description: export default defines the default export of the component. When importing, components are automatically imported. Simplify the import process, improve clarity and prevent conflicts. Commonly used for exporting individual components, using both named and default exports, and registering global components.

How to use map function in vue How to use map function in vue May 09, 2024 pm 06:54 PM

The Vue.js map function is a built-in higher-order function that creates a new array where each element is the transformed result of each element in the original array. The syntax is map(callbackFn), where callbackFn receives each element in the array as the first argument, optionally the index as the second argument, and returns a value. The map function does not change the original array.

The development history of wireless mice The development history of wireless mice Jun 12, 2024 pm 08:52 PM

Original title: "How does a wireless mouse become wireless?" 》Wireless mice have gradually become a standard feature of today’s office computers. From now on, we no longer have to drag long cords around. But, how does a wireless mouse work? Today we will learn about the development history of the No.1 wireless mouse. Did you know that the wireless mouse is now 40 years old? In 1984, Logitech developed the world's first wireless mouse, but this wireless mouse used infrared as a The signal carrier is said to look like the picture below, but later failed due to performance reasons. It was not until ten years later in 1994 that Logitech finally successfully developed a wireless mouse that works at 27MHz. This 27MHz frequency also became the wireless mouse for a long time.

The difference between export and export default in vue The difference between export and export default in vue May 08, 2024 pm 05:27 PM

There are two ways to export modules in Vue.js: export and export default. export is used to export named entities and requires the use of curly braces; export default is used to export default entities and does not require curly braces. When importing, entities exported by export need to use their names, while entities exported by export default can be used implicitly. It is recommended to use export default for modules that need to be imported multiple times, and use export for modules that are only exported once.

The role of onmounted in vue The role of onmounted in vue May 09, 2024 pm 02:51 PM

onMounted is a component mounting life cycle hook in Vue. Its function is to perform initialization operations after the component is mounted to the DOM, such as obtaining references to DOM elements, setting data, sending HTTP requests, registering event listeners, etc. It is only called once when the component is mounted. If you need to perform operations after the component is updated or before it is destroyed, you can use other lifecycle hooks.

The main peak of Changbai Mountain can access the Internet normally: Jilin Mobile and ZTE completed 2.6G + 700M three-carrier aggregation for commercial use, with a peak rate of more than 2.53Gbps The main peak of Changbai Mountain can access the Internet normally: Jilin Mobile and ZTE completed 2.6G + 700M three-carrier aggregation for commercial use, with a peak rate of more than 2.53Gbps Jul 25, 2024 pm 01:20 PM

According to news on July 25, Jilin Mobile and ZTE have completed commercial use of three-carrier aggregation based on the 2.6G frequency band (100+60M) and the 700M frequency band (30M) on the main peak of Changbai Mountain. The peak rate in field testing can reach more than 2.53Gbps. Officials pointed out that Changbai Mountain is one of the top ten famous mountains in China. It is now a national AAAAA tourist attraction, a world geological park, a world biosphere reserve, and the world's best nature reserve. The number of tourists received in 2023 will reach 2.7477 million, and 3CC will be deployed this time. It will greatly meet users’ network needs. According to reports, Jilin Mobile has taken the lead in completing the carrier aggregation pilot of a three-carrier network in the 2.6G (100+60M) plus 4.9G (100M) frequency band in early 2024, with peak downloads

What are hooks in vue What are hooks in vue May 09, 2024 pm 06:33 PM

Vue hooks are callback functions that perform actions on specific events or lifecycle stages. They include life cycle hooks (such as beforeCreate, mounted, beforeDestroy), event handling hooks (such as click, input, keydown) and custom hooks. Hooks enhance component control, respond to component life cycles, handle user interactions and improve component reusability. To use hooks, just define the hook function, execute the logic and return an optional value.

See all articles