Home > Article > Web Front-end > How to use eventbus in vue
EventBus is a communication mechanism in Vue.js that allows non-parent-child communication between components. Usage includes: Create a global EventBus instance. Use eventBus.$emit() to trigger events. Use eventBus.$on() to listen for events. Its advantages include non-parent-child communication, loose coupling, and scalability.
Usage of EventBus in Vue.js
EventBus is a communication mechanism in Vue.js that allows Non-parent-child communication between components. It delivers events and data through a centralized event bus.
Installation
EventBus is an independent package and needs to be installed first:
<code class="bash">npm install --save vue-eventbus</code>
Usage
Using EventBus in a Vue.js application is very simple.
1. Create an EventBus instance
Create a global EventBus instance, usually in the main.js
file:
<code class="javascript">import Vue from "vue"; import VueEventBus from "vue-eventbus"; Vue.use(VueEventBus); // 使用 EventBus 的全局实例 const eventBus = new VueEventBus();</code>
2. Trigger events
<code class="javascript">eventBus.$emit("my-event", data);</code>
3. Listen for events
<code class="javascript">export default { mounted() { eventBus.$on("my-event", (data) => { // 处理事件 }); }, };</code>
Advantages
Notes
The above is the detailed content of How to use eventbus in vue. For more information, please follow other related articles on the PHP Chinese website!