vue非父子组件之间的通信:bus总线(中央发布令)

1、bus总线中央发布令

在这里插入图片描述
如图所示,加入组件:1–3需要进行数据传递,一般情况下会通过组件2作为中间者,进行传值;但如果组件:3–3也需要通信,这时候再通过3向上传,一层一层是非常复杂的;vue是一个轻量级的框架,遇到复杂的数据处理时,需要借助其他工具;
这里我们使用 bus 总线(中央发布令)
代码示例:已下代码中列举了两种组件之间通过change事件进行通信;

首先将bus挂载到vue实例中
Vue.prototype.bus = new Vue();

//组件一:

Vue.component('one',{
    props:{
        temContent:String
    },
    data:function () {
        return{
            content:this.temContent
        }
    },
    template:`<div>
    <p @click="handleClick">{{content}}</p>
    </div>`,
    methods:{
        handleClick:function () {
            this.bus.$emit('change',this.content);
            this.bus.$emit('samechange',this.content)
        },

    },
    mounted:function () {
        var self = this;
        this.bus.$on('change',function (msg) {
        //do something
            self.content = msg
        });
        this.bus.$on('samechange',function (msg) {
                //do somthing
            })
    }
});


//组件二

Vue.component('two', {template:`<div @click="handleClick"><div>{{content}}</div></div>`,

props:{
    tempContent:{
        type:String,
    }
},
data:function(){
    return{
        content:this.tempContent
    }
},
methods:{
    handleClick:function(){  
    //do somthing
    this.bus.$emit('change',this.tempContent)
    }
},
mounted:function () {
    var self = this;
    this.bus.$on('change',function (msg) {
    //do somthing
        self.tempContent = msg
    })
}
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值