事件总线传递思想:就是把事件绑定在这两个兄弟共同访问Vue的实例对象上面
第一步:先创建两个子组件,并在Index.vue文件中引入
<template>
<div>
<!-- 兄弟传参需要在 main.js 中写实例对象做桥梁 -->
<bus-che-01></bus-che-01>
<bus-che-02></bus-che-02>
</div>
</template>
<script>
import BusChe01 from './BusChe01.vue'
import BusChe02 from './BusChe02.vue'
export default {
components: { BusChe01, BusChe02 },
}
</script>
<style lang="scss" scoped>
</style>
第二步:在router中添加路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Demo02 from '../views/Demo02/Index.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/demo02',
name: 'Demo02',
component: Demo02
},
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
第三步:在main.js里创建自定义$EventBus对象,并存放在原型(prototype)里 
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
// 事件总线:兄弟传参
const EventBus = new Vue();
// 在原型(prototype)里添加这个实例
Vue.prototype.$EventBus = EventBus
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
第四步: 在BusChe01.vue中先绑定一个变量str,通过输入触发search方法
<template>
<div>
<input type="text" v-model="str" @input="search">
</div>
</template>
<script>
export default {
data() {
return {
str: ''
}
},
methods: {
search() {
this.$EventBus.$emit('search', this.str) // 事件总线:'$EventBus'为自定义
// this.$parent.$emit('search', this.str)
// this.$root.$emit('search', this.str)
}
},
}
</script>
<style lang="scss" scoped>
</style>
第五步:在兄弟关系(BusChe02.vue)组件中挂载(mounted)绑定一个事件($on),通过事件函数去触发,让变量str去接收响应结果
<template>
<div>
{{str}}
</div>
</template>
<script>
export default {
data() {
return {
str: ''
}
},
mounted () {
// 兄弟传参方法1:事件总线
this.$EventBus.$on('search',(str)=>{
this.str = str;
})
// 事兄弟传参方法2:$parent
// 把事件绑定到一个兄弟组件可以访问的公共vue实例对象上
// this.$parent.$on('search',(str)=>{
// this.str = str;
// })
// 事兄弟传参方法3(不常用):$root
// console.log(this.$root)
// this.$root.$on('search',(str)=>{
// this.str = str;
// })
},
}
</script>
<style lang="scss" scoped>
</style>
第六步:最终效果 