Vue之中央事件总线bus

中央事件总线bus

  • 简介:一种适用于任意组件间通信的方式

  • 如何理解:将其想象成卖房中介,在租户和房东之间跑腿的人就行

  • 安装

    new Vue({
    	......
    	beforeCreate() {
    		Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
    	},
        ......
    }) 
    
  • 使用事件总线

    1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.$bus.$on('xxxx',this.demo)
      }
      
    2. 提供数据:this.$bus.$emit('xxxx',数据)

  • 解绑时机:在beforeDestroy钩子中,用$off去解绑当前当前组件所用到的事件。

  • 示例

    <div id="app">
    			<component-a></component-a>
    			<br/>
    			<component-b></component-b>
    			<button @click="sendMessage">点我向儿子组件发送数据</button>
    		</div>
    		<script type="text/javascript" src="../js/vue.js">
    		</script>
    		<script type="text/javascript">
    			var app = new Vue({
    				el:'#app',
    				data:{
    					message:'我是根组件的数据'
    				},
    				components:{
    					'component-a':{
    						template:'<div>\
    						这是来自根组件的信息:{{messageRoot}}<br/>\
    						这是来自兄弟组件的信息:{{messageBrother}}\
    						</div>',
    						data:function(){
    							return {
    								messageRoot:'',
    								messageBrother:''
    							}
    						},
    						methods:{
    							getRootMessage:function(message){
    								this.messageRoot = message;
    							},
    							getBrotherMessage:function(message){
    								this.messageBrother = message;
    							}
    						},
    						mounted:function(){
    							// 给bus绑定自定义事件,回调留在自身,说明我想获得数据
    							this.$bus.$on('RootMessage', this.getRootMessage); 
    							this.$bus.$on('BrotherMessage', this.getBrotherMessage);
    						}
    					},
    					'component-b':{
    						template:'<div>\
    							<button @click="sendMessage">点我向兄弟组件发送数据</button>\
    						</div>',
    						data:function(){
    							return {
    								message:'我是兄弟组件的数据'
    							}
    						},
    						methods:{
    							sendMessage(){
    								this.$bus.$emit('BrotherMessage', this.message);
    							}
    						}
    					}
    				},
    				methods:{
    					sendMessage(){
    						this.$bus.$emit('RootMessage', this.message);
    					}
    				},
    				beforeCreate(){
    					Vue.prototype.$bus = this; // 安装中央事件总线bus
    				}
    			})
    		</script>
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小陌白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值