-
EventBus实例:
var EventBus = new Vue()
会创建一个名为EventBus的Vue实例,并将其存储在变量EventBus中。Vue.prototype.$bus = new Vue()
则直接在Vue的原型上创建一个新的Vue实例,并将其赋值给$bus属性。
-
使用方式:
var EventBus = new Vue()
的方式需要你手动导入EventBus实例到需要使用的组件中。Vue.prototype.$bus = new Vue()
的方式则无需手动导入,因为$bus已经成为Vue原型的一部分,你可以在任何组件中直接使用this.$bus来访问该实例。
-
作用域和生命周期:
var EventBus = new Vue()
创建的EventBus实例的生命周期由你手动管理,需要在适当的时候进行销毁。Vue.prototype.$bus = new Vue()
创建的$bus实例则随着Vue应用的生命周期一起管理,当Vue实例被销毁时,$bus实例也会被销毁。
因此,虽然这两种方式都可以实现全局事件总线的功能,但在使用上有一些细微的差别。Vue.prototype.$bus = new Vue()
更加简洁和方便,特别适合在Vue项目中实现全局事件总线的需求。
EventBus实例
创建一个名为EventBus的Vue实例(/utils/event-bus.js)
import Vue from 'vue'
export const EventBus = new Vue()
在A组件中的使用
<button @click="sendMsg">按钮</button>
// 导入EventBus
import { EventBus } from '@/utils/event-bus.js'
sendMsg() {
// 发送名为'sendMsg'的事件,可以携带额外的数据
EventBus.$emit('sendMsg', 'hello')
}
在B组件中的使用
// 导入EventBus
import { EventBus } from '@/utils/event-bus.js'
created() {
// 监听名为'sendMsg'的事件
EventBus.$on('sendMsg', (msg) => {
// 处理接收到的事件数据
this.msg = msg
})
},
beforeDestroy() {
// 在组件销毁前取消事件监听,以避免内存泄漏
EventBus.$off('sendMsg')
}
$bus实例
var EventBus = new Vue();
这一行代码创建了一个名为 EventBus 的新的 Vue 实例。这个实例将作为我们的事件总线,用于在 Vue 组件之间进行事件通信。
Object.defineProperties(Vue.prototype, { $bus: { get: function () { return EventBus } } })
这段代码使用 Object.defineProperties 方法将 $bus 属性添加到 Vue 的原型上。
定义了 $bus 属性的 get 方法,当我们在组件中使用 this.$bus 访问时,实际上是在获取 EventBus 这个 Vue 实例。
通过在 main.js
中执行这段代码,我们就可以在整个 Vue 应用中使用 this.$bus
来访问事件总线实例,方便地实现组件之间的事件通信。
$bus实例(简洁版)
在 main.js 中添加 $bus:
在 Vue 应用的入口文件 main.js 中添加以下代码:
import Vue from 'vue';
// 创建一个全局的事件总线并挂载到 Vue 原型上
Vue.prototype.$bus = new Vue();
发送事件:
在任何组件中,可以使用 this.$bus.$emit
发送事件。例如:
export default {
methods: {
handleClick() {
// 发送名为 'custom-event' 的事件,可以携带额外的数据
this.$bus.$emit('custom-event', eventData);
}
}
};
监听事件:
在需要监听事件的组件中,使用 this.$bus.$on
方法监听事件。例如:
export default {
created() {
// 监听名为 'custom-event' 的事件
this.$bus.$on('custom-event', this.handleCustomEvent);
},
methods: {
handleCustomEvent(data) {
// 处理接收到的事件数据
console.log('Received custom event:', data);
}
},
beforeDestroy() {
// 在组件销毁前取消事件监听,以避免内存泄漏
this.$bus.$off('custom-event', this.handleCustomEvent);
}
};