$bus 事件总线:Vue.js 组件间通信指南
$bus 事件总线:Vue.js 组件间通信指南
$bus 是一种事件总线,它在 Vue.js 应用程序中提供了一种在组件之间进行通信的有效方式。通过使用 $bus,你可以在一个组件中触发一个事件,并在另一个组件中监听该事件,然后执行相应的处理函数。
使用步骤
- 创建事件总线: 在你的 Vue 实例中创建一个新的 Vue 对象作为你的事件总线。
const bus = new Vue();
- 发送事件: 在发送事件的组件中,使用
$emit方法触发事件。
bus.$emit('my-event', arg1, arg2);
- 监听事件: 在接收事件的组件中,使用
$on方法监听事件,并提供一个处理函数来处理事件。
bus.$on('my-event', (arg1, arg2) => {
// 处理事件
});
- 取消监听: 在组件销毁时,使用
$off方法取消事件监听,以防止内存泄漏。
bus.$off('my-event');
注意事项
- $bus 是一个全局事件总线,因此可以在任何组件中使用。
- 确保在组件销毁时取消事件监听,以避免内存泄漏。
- 为了更好地管理事件订阅和取消订阅,建议在组件中使用
created和destroyed这样的生命周期钩子函数。
示例
// 父组件
<template>
<div>
<button @click="sendEvent">发送事件</button>
<child-component></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
sendEvent() {
bus.$emit('my-event', 'Hello from parent');
}
}
};
</script>
// 子组件
<template>
<div>
{{ message }}
</div>
</template>
<script>
export default {
mounted() {
bus.$on('my-event', (msg) => {
this.message = msg;
});
},
beforeDestroy() {
bus.$off('my-event');
},
data() {
return {
message: ''
};
}
};
</script>
通过 $bus,你可以轻松地在 Vue.js 应用程序的组件之间进行通信,并构建更强大的应用程序。
原文地址: https://www.cveoy.top/t/topic/mKfL 著作权归作者所有。请勿转载和采集!