当前位置: 首页> 游戏> 游戏 > 网络优化方案_平面设计找工作_百度安装_文明seo技术教程网

网络优化方案_平面设计找工作_百度安装_文明seo技术教程网

时间:2025/7/9 12:23:44来源:https://blog.csdn.net/michael_jovi/article/details/145075499 浏览次数:1次
网络优化方案_平面设计找工作_百度安装_文明seo技术教程网

在Vue.js中,EventBus是一种用于组件间通信的方式,特别是在没有父子关系的组件之间。我们可以创建一个空的Vue实例来作为事件总线。

实例:

展示如何使用EventBus实现两个兄弟组件之间的通信。

首先,我们需要创建一个EventBus:

import Vue from 'vue';
export const EventBus = new Vue();

接下来,创建两个兄弟组件,并通过EventBus进行通信。假设这两个组件分别是ComponentA.vueComponentB.vue

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Vue EventBus Example</title><script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body><div id="app"><component-a></component-a><component-b></component-b></div><script>// 创建一个EventBusconst EventBus = new Vue();// 定义ComponentAVue.component('component-a', {template: `<div><h3>Component A</h3><button @click="sendMessage">Send Message to Component B</button></div>`,methods: {sendMessage() {EventBus.$emit('message-from-a', 'Hello from Component A!');}}});// 定义ComponentBVue.component('component-b', {data() {return {message: ''};},template: `<div><h3>Component B</h3><p>{{ message }}</p></div>`,created() {EventBus.$on('message-from-a', (msg) => {this.message = msg;});}});// 初始化Vue实例new Vue({el: '#app'});</script>
</body>
</html>

说明:

这个例子中,ComponentA有一个按钮,当点击这个按钮时,会触发一个名为message-from-a的事件,并传递一条消息给其他监听该事件的组件。ComponentB在创建时开始监听这个事件,并在其回调函数中更新自己的数据属性message,从而显示从ComponentA接收到的消息。

关键字:网络优化方案_平面设计找工作_百度安装_文明seo技术教程网

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: