当前位置 博文首页 > 超负荷小生的博客:vue2.0---使用eventBus实现兄弟组件之间的通

    超负荷小生的博客:vue2.0---使用eventBus实现兄弟组件之间的通

    作者:[db:作者] 时间:2021-09-08 19:41

    简述

    使用eventBus实现兄弟组件的通信,使用以下三个文件,完成两个子组件(兄弟组件)之间的通信

    文件名称使用情况
    FirstSon.vue第一个子组件,作为接收方:接收消息
    About.vue第二个子组件,作为发送方:发送数据
    默认的App.vue作为父组件调用以上两个子组件

    实现

    第一步: 创建EvenBus.js文件,并在main.js中导入该文件

    import Vue from 'vue'
    //创建一个局部的vue实例
    const eventbus = new Vue();
    //把实例给Vue的原型,实现全局挂载,使用时不用在组件中进行import导入操作
    Vue.prototype.$eventbus=eventbus;
    
    export default eventbus;
    

    main.js中导入

    //根据main.js和EventBus.js两个文件的位置在main中进行对应的导入
    import './EventBus.js'
    

    第二步: 用About.vue页面向FirstSon.vue发起通信。
    ① 可以编写一个button按钮触发函数发起通信
    ② 使用mounted钩子函数:模板渲染完成以后才会被调用

    <template>
      <div class="about">
        <h1>This is an about page</h1>
    	<!-- 使用button按钮 -->
    	<button @click.stop.prevent="aboutChange()">发送</button>
      </div>
    </template>
    
    <script>
    	export default{
    		methods:{
    			aboutChange(){
    				this.$eventbus.$emit('changeTitle','About-Button传输数据')
    			}
    		},
    		mounted() {
    			this.$eventbus.$emit('changeTitle','About钩子函数传输数据')
    		}
    	}
    </script>
    

    第三步: 兄弟组件FirstSon.vue接收数据

    <template>
    	<div>
    		<header>
    			<h2>{{title}}</h2>
    		</header>
    	</div>
    </template>
    <script>
    	export default {
    		data() {
    			return {
    				title: '这是firstSon子组件'
    			}
    		},
    		mounted() {
    			//写法一
    			/*
    			this.$eventbus.$on('changeTitle', function(str) {
    				this.title = str;
    			 }.bind(this));
    			*/
    		   
    			//写法二
    			this.$eventbus.$on('changeTitle',str =>{
    				this.title = str;
    			});
    		}
    	}
    </script>
    

    第四步: 父组件App.vue 引用两个子组件即可

    <template>
      <div id="app">
        <!--跳转使用-->
        <div id="nav">
          <router-link to="/">router-link-Home</router-link> |
          <router-link to="/about">router-link-About</router-link>
        </div>
    	<Son></Son> <!--使用firstSon组件-->
        <router-view/> <!--路由到其他的组件其中包括About.vue组件-->
    	
      </div>
    </template>
    <script>
    	import Son from './components/FirstSon.vue';
    	export default{
    		components:{
    			Son
    		}
    	}
    </script>
    

    效果图

    初次访问
    在这里插入图片描述点击router-link-About以后
    在这里插入图片描述点击按钮以后
    在这里插入图片描述

    cs