兄弟组件间的传值 - $bus

本文介绍了如何在Vue应用中利用$bus(事件总线)进行兄弟组件之间的通信,通过创建一个Vue实例并注册到原型,简化了组件间的数据传递,展示了发布/订阅模式的实际操作和示例代码。

兄弟组件间的传值 - $bus

兄弟组件之间的传值方式有很多,例如很方便的 vuex,或者通过传父组件再传兄弟组件,这里介绍 vue 中的 $bus 的使用方法

首先在 main.js 中创建一个新 vue 实列

import Vue from 'vue'
import App from './App'
import router from './router'

import Vant from 'vant';
import 'vant/lib/index.css';

Vue.prototype.$bus = new Vue({

})  //创建一个 vue 实例,将 $bus 注册到 vue 的 prototype 上

new Vue({
  router,
  Vant,
  render: h => h(App)
}).$mount('#app')

创建 brother.vue 文件作为要传入的兄弟组件

<template>
    <div>
        我是兄弟组件
    </div>
</template>
<script>
export default {
    created(){
        this.$bus.$on('fun',this.brotherL)  //监听事件 fun,定义自己的方法 brotherL 来获取传递过来的值
    },
    methods: {
        brotherL(e){
            console.log(e)  //打印兄弟组件传过来的值
        }
    }
}
</script>

再创建 child.vue 作为子组件,它的兄弟组件就是 brother

<template>
    <div>
        我是孩子组件
        <button @click="sayLove()">向兄弟表白</button>  //绑定传值方法,点击按钮触发 sayLove方法
    </div>
</template>
<script>
export default {
    data(){
    },
    methods:{
        sayLove(){
            this.$bus.$emit('fun','i love u')  //向兄弟组件发布事件 fun,传递参数为 i love u
        }
    }
}
</script>

在父组件中注册 child 和 brother 组件

<template>
<div id="app">
  <Child></Child>
  <Brother></Brother>
    <router-view/>
</div>
</template>
<script>
import Child from './components/child.vue'
import Brother from './components/brother.vue'
export default {
  name: 'App',
  components:{
    Child,
    Brother
  }
}
</script>

点击按钮,打印 i love u
在这里插入图片描述
在 vue.prototype 中注册 $bus 事件用于兄弟组件传值,本质上是一个发布订阅的模式:

emit — 发布消息,通知订阅中心有数据更新,也就是发射事件
on — 添加订阅者,也就是监听事件

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值