兄弟组件间的传值 - $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 — 添加订阅者,也就是监听事件