Vue非父子组件间的通信(bus中央事件总线)

Main.js

首先在Main.js中创建中央事件总线bus

Vue.prototype.bus = new Vue()
复制代码
父组件
<template>
    <child1></child1>
    <child2></child2>
</tempalte>

<script>
    import childComponent from './components/child1'
    import childComponent from './components/child2'
    export default(){
        name:'App',
        components:{
            child1,
            child2
        }
    }
</script>
复制代码
组件1

通过this.bus.$emith传递数据

<template>
   <h1 @click="ch1">{{child1msg}}</h1>
</tempalte>

<script>
    export default(){
        name:'child1',
        data(){
            return{
                child1msg:'我是组件1的数据'
                
            }
        },
        methods:{
            ch1(){
                this.bus.$emit('message',this.child1msg)
            }
        }
        
    }
</script>
复制代码
组件2

在生命周期函数created或者mounted中获取 通过this.bus.$on('message',function(res){ console.log(res) //res就是组件1传过来的值 })

<template>
   <h1 @click="ch2">{{child2msg}}</h1>
</tempalte>

<script>
    export default(){
        name:'child2',
        data(){
            return{
                child2msg:'我是组件1的数据'
                
            }
        },
        created(){
            let _this = this
            this.bus.$on('message',function(res){
                _this.child1msg = res
            })
        }
        
    }
</script>
复制代码

转载于:https://juejin.im/post/5d06fe86e51d455071250b07

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值