通过$emit和$on,vue实现兄弟组件通讯

首先在src目录下建一个config文件夹,文件夹里面放一个eventroot.js文件,再建两个组件(兄弟组件),

目录如下:

eventroot.js里面new出来的空的vue实例,代码如下

import Vue from 'vue';
export default new Vue;

didi.vue代码:

<template>
  <div class="brother" @click="didi" :style="{color:data}">我是弟弟,改变哥哥的字体大小</div>
</template>
<script>
  import rootvue from '@/config/eventroot.js'
    export default {
        name: "didi",
      props:['data'],
      methods:{
        didi(){
          rootvue.$emit('didi',{
            msg:'我是弟弟',fontsize:'30px'
          });
        }
      }
    }
</script>
<style scoped></style>

gege.vue代码:

<template>
    <div class="brother" @click="gege" :style="{fontSize:data}">我是哥哥,改变弟弟的字体颜色</div>
</template>
<script>
  import rootvue from '@/config/eventroot.js'
    export default {
        name: "gege",
      props:['data'],
      methods:{
          gege(){
            rootvue.$emit('gege',{
              msg:'我是哥哥',color:'red'
            });
          }
      }
    }
</script>
<style scoped></style>

App.vue代码

<template>
  <div>
   <gege :data="fontsize"></gege>
    <didi :data="color"></didi>
  </div>
</template>
<script>
  import rootvue from '@/config/eventroot.js'
  import Gege from "../components/brother/gege";
  import Didi from "../components/brother/didi";

    export default {
        name: "list",
      data(){
          return{
            fontsize:'12px',
            color:'#333'
          }
      },
      components: {Didi, Gege},
      mounted(){
        rootvue.$on('gege',(val) =>{
          this.color = val.color;
        });
        rootvue.$on('didi',(val) =>{
          this.fontsize = val.fontsize;
        });
      },
      beforeDestroy () {       
        rootvue.$off('gege')
        rootvue.$off('didi')
      }
    }
</script>
<style scoped></style>

默认显示:

运行的结果(先点击哥哥,再点击弟弟的结果):

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值