组件通信(父传子,子传父,兄弟传值)

一、父传子

父组件:<son :msg=“fatherMsg”></son>
子组件:props:[‘msg’]

//父组件
<template>
    <div>
        <son :msg="fatherMsg"></son>
    </div>
</template>
<script>
import son from './son'
export default {
    data(){
        return {
            fatherMsg:'父组件的msg',
        }
    },
    components:{
        son
    }
}
</script>


//子组件
<template>
    <div>
        子组件收到的消息:{{msg}}
    </div>
</template>
<script>
export default {
    props:['msg'],
}
</script>

二、子传父

父组件:
<son @自定义事件名称=“方法”></son>

子组件:
props:[‘自定义事件名称’]
this.$emit(自定义事件名称,要传的数据)

//父组件
<template>
    <div>
        <son @send="send"></son>
    </div>
</template>
<script>
import son from './son'
export default {
    components:{
        son
    },
    methods:{
        send(msg){
            console.log('父组件收到的消息:'+msg)
        },
    },
}
</script>


//子组件
<template>
    <div>
        <button @click="toFather">发送给父组件</button>
    </div>
</template>
<script>
export default {
    props:['send'],
    methods:{
        toFather(){
            this.$emit('send','子组件的msg')
        }
    },
}
</script>

三、兄弟组件传值

通过一个中转(bus):
import Vue from ‘vue’
export default new Vue;

A兄弟传值:
import bus from ‘@/common/bus.js’
bus.$emit(‘toBorther’,this.msg)

B兄弟接收:
import bus from ‘@/common/bus.js’
bus.$on(‘toBorther’,(data)=>{
this.msg=data
})

//父组件
<template>
  <div class="about">
    <!-- 兄弟组件传值 -->
    <sister></sister>
    <brother></brother>
  </div>
</template>

<script>
import sister from '../components/sister'
import brother from '../components/brother'
export default {
  data(){
    return{

    }
  },
  components:{
    sister,
    brother
  },
}
</script>


//中转(bus.js)
import Vue from 'vue'
export default new Vue;


//A组件(sister.vue)
<template>
    <div>
        <button @click="send">发送参数</button>
    </div>
</template>
<script>
import bus from '@/common/bus.js'
export default {
  data(){
    return{
      msg:"这是A的数据"
    }
  },
    methods:{
        send(){//发送参数
            bus.$emit('toBorther',this.msg)
        }
    },
}
</script>


//B组件(borther.vue)
<template>
    <div>
        {{msg}}
    </div>
</template>
<script>
import bus from '@/common/bus.js'
export default {
  data(){
    return{
      msg:'',
    }
  },
  mounted(){
    bus.$on('toBorther',(data)=>{//接收参数
      this.msg=data
    })
  },
}
</script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值