先在main.js里定义一个新的实例
//定义$bus
Vue.prototype.$bus=new Vue()
在子组件里自定义方法,通过$bus.$emit
向兄弟组件传值
子组件
<template>
<div>
<h1>儿子组件</h1>
<button @click="say">表达爱意</button>
</div>
</template>
<script>
export default {
methods:{
say(){
this.$emit('say','hello father')
this.$bus.$emit('sayToBro','hello brother')
}
}
}
</script>
<style>
</style>
在兄弟组件里通过$bus.$on
监听自定义事件sayToBro接受子组件里的值
兄弟组件
<template>
<div>
<h2>兄弟组件</h2>
</div>
</template>
<script>
export default {
created(){
this.$bus.$on('sayToBro',this.getLove)
},
methods:{
getLove(e){
console.log('兄弟组件',e)
}
}
}
</script>
<style>
</style>
在父组件里引入子组件和兄弟组件
父组件
<template>
<div>
<h1>父亲组件</h1>
<children @say="getHello"></children>
<brother >表达爱意</brother>
</div>
</template>
<script>
import Children from './Children.vue'
import Brother from './Brother.vue'
export default {
data(){
return{
mylove:''
}
},
components:{
Children,
Brother
},
methods:{
getHello(e){
console.log(e);
this.mylove=e
}
}
}
</script>
<style>
</style>