一、通过EventBus进行兄弟间组件通讯
1.通过 import 引入vue公共实例
1)在main.js
文件中定义一个新的eventBus
对象,其实他是一个全新的Vue
实例:
export const eventBus = new Vue();
2)兄弟组件A.vue
import { eventBus } from '@/main'
//监听事件
created() {
eventBus.$on('showMenus', (arg) => {
console.log('123'+arg);
alert(arg);
})
},
3)兄弟组件B.vue
import { eventBus } from '@/main'
//分发事件传值
methods: {
switchmenu:function(flag){
eventBus.$emit('showMenus',flag); //触发事件
}
}
2.通过 window传递vue公共实例
1)在main.js
文件中实例化一个Vue
对象,并把它赋值于window.eventBus
,这样eventBus
就可以在任何组件中使用:
window.eventBus = new Vue();
2)兄弟组件A.vue
//监听事件
export default {
created() {
eventBus.$on('showMenus', (arg) => {
console.log('123'+arg);
alert(arg);
})
}
}
3)兄弟组件B.vue
export default {
//分发事件传值
methods: {
switchmenu:function(flag){
eventBus.$emit('showMenus',flag); //触发事件
}
}
}
二、通过父级组件进行兄弟间组件通讯
1.父组件:
<!-- ParentCard.vue -->
<template>
<div class="card">
<div class="card-body">
<brother-card :messageSon="messageson"
@brotherSaid="messageDaughter($event)"></brother-card>
<sister-card :messageDaughter="messagedaughter"
@sisterSaid="messageSon($event)"></sister-card>
</div>
</div>
</template>
<script>
import BrotherCard from './BrotherCard';
import SisterCard from './SisterCard'
export default {
name: 'ParentCard',
data: () => ({
theCardTitle: '父组件',
messagedaughter:'',
messageson:''
}),
components: {
BrotherCard,
SisterCard
},
methods: {
messageDaughter(message) {
this.messagedaughter = message;
},
messageSon(message) {
this.messageson = message;
},
stopFighting() {
if (this.messagedaughter && this.messageson) {
return true
}
return false
},
momSaidChill() {
this.messagedaughter = '',
this.messageson = ''
}
}
};
</script>
2.哥哥组件
<!-- BrotherCard.vue -->
<template>
<div class="message">
<div class="message-header">
<h5 v-text="theCardTitle"></h5>
</div>
<div class="message-body">
<p class="message-text">我是Brother组件</p>
<button @click="messageSister" class="btn">给妹妹发消息</button>
<div v-if="messageSon" class="alert" v-html="messageSon"></div>
</div>
</div>
</template>
<script>
export default {
name: 'BrotherCard',
props: ['messageSon'],
data: () => ({
theCardTitle: '子组件1'
}),
methods: {
messageSister() {
this.$emit('brotherSaid', '妈妈说,该做作业了!(^_^)!!!')
}
}
}
</script>
3.妹妹组件
<!-- SisterCard.vue -->
<template>
<div class="message">
<div class="message-header">
<h5 v-text="theCardTitle"></h5>
</div>
<div class="message-body">
<p class="message-text">我是Sister组件</p>
<button @click="messageBrother" class="btn">给哥哥发消息</button>
<div v-if="messageDaughter" class="alert" v-html="messageDaughter"></div>
</div>
</div>
</template>
<script>
export default {
name: 'SisterCard',
props: ['messageDaughter'],
data: () => ({
theCardTitle: '子组件2'
}),
methods: {
messageBrother() {
this.$emit('sisterSaid', '妈妈说,该做作业了!(^_^)!!!')
}
}
}
</script>
总结:
参考资料:Vue组件通讯:https://www.w3cplus.com/vue/component-communication.html
网友评论