兄弟组件
第一种
子 B
<template>
<input @input='handleInput' :value='value'>
</template>
<script>
export default{
props:{
value:{
type:[String,Number],
default:''
}
},
methods:{
handleInput(e){
const val = e.target.value
this.emit('input',val)
}
}
}
</script>
子 C
<template>
<div>{{val}}</div>
</template>
<script>
export default{
props:{
value:{
type:[String,Number],
default:''
}
}
}
</script>
父 A
<template>
<div class="home">
<h-b @input='handleInput'/>
<h-c :value = 'val' />
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
val: ""
};
},
components: {
hB:()=>import("@/components/B.vue"),
hC:()=>import("@/components/C.vue"),
},
methods:{
handleInput(val){
this.val = val
}
}
};
</script>
第二种
bus.js
import Vue from 'vue'
const bus=new Vue()
export default bus
子 A
<template>
<div>
<button @click='emitMessage'>传给兄弟组件信息</button>
</div>
</template>
<script>
import bus from './bus.js'
export default{
data(){
return{
title:'子组件A'
}
},
methods:{
emitMessage(){
bus.$emit('theMessage',this.title)
}
}
}
</script>
子 B
<template>
<div>
<h1>{{title}}</h1>
</div>
</template>
<script>
import bus from './bus.js'
export default{
data(){
return{
title:'子组件B'
}
},
mounted(){
bus.$on('theMessage',res=>{
console.log(res)
this.title = res
})
}
}
</script>
父 App
<template>
<div>
<A/>
<B/>
</div>
</template>
<script>
import A from './views/A.vue'
import B from './views/B.vue'
export default{
components:{
A,
B
}
}
</script>
第三种
Bus.js
import Vue from 'vue'
const bus=new Vue()
export default bus
main.js
import bus from './bus'
Vue.prototype.$bus=bus
子 A
<template>
<div>
<button @click='emitMessage'>传给兄弟组件信息</button>
</div>
</template>
<script>
export default{
data(){
return{
title:'子组件A'
}
},
methods:{
emitMessage(){
this.$bus.$emit('getMessage',this.title)
}
}
}
</script>
子 B
<template>
<div>
<h1>{{title}}</h1>
</div>
</template>
<script>
export default{
data(){
return{
title:''
}
},
mounted(){
this.$bus.$on('getMessage',data=>{
this.title = data
})
}
}
</script>