Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue2 eventbus

作者:发光男神   发布日期:2025-03-27   浏览:92

// 创建一个 Vue 实例作为事件总线
const EventBus = new Vue();

// 发布事件
function publishEvent() {
  // 使用 $emit 触发事件,并传递参数
  EventBus.$emit('custom-event', { message: 'Hello from event bus!' });
}

// 订阅事件
function subscribeEvent() {
  // 使用 $on 监听事件,并在触发时执行回调函数
  EventBus.$on('custom-event', (data) => {
    console.log(data.message); // 输出: Hello from event bus!
  });
}

// 在组件中使用事件总线
Vue.component('child-component', {
  template: '<div @click="handleClick">Click me to trigger an event</div>',
  methods: {
    handleClick() {
      // 触发事件
      publishEvent();
    }
  }
});

Vue.component('parent-component', {
  mounted() {
    // 监听事件
    subscribeEvent();
  },
  template: '<child-component></child-component>'
});

new Vue({
  el: '#app',
  template: '<parent-component></parent-component>'
});

解释说明

  1. 创建事件总线

    • EventBus 是一个 Vue 实例,用于在不同组件之间进行通信。
  2. 发布事件

    • publishEvent 函数通过 EventBus.$emit 方法触发一个名为 custom-event 的事件,并传递一个对象作为参数。
  3. 订阅事件

    • subscribeEvent 函数通过 EventBus.$on 方法监听 custom-event 事件,并在事件触发时执行回调函数。
  4. 组件间的通信

    • child-component 组件中定义了一个点击事件,点击后会调用 publishEvent 发布事件。
    • parent-component 组件在挂载时调用 subscribeEvent 监听事件,当事件被触发时会输出相应的消息。

通过这种方式,可以实现父子组件或其他不直接相关的组件之间的通信。

上一篇:vue markraw

下一篇:vue 阻止事件冒泡

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站