首先在main.js
文件中定义一个新的eventBus
对象,其实他是一个全新的Vue实例:
export const eventBus = new Vue()
接着在新创建的BrotherCard、SisterCard
组件导入main.js
:
<script>
import { eventBus } from '../main'
</script>
<!-- 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="fromBrother" class="alert" v-html="fromBrother"></div>
</div>
</div>
</template>
<script>
import { eventBus } from "../main";
export default {
name: "SisterCard",
data: () => ({
theCardTitle: "Sister Card",
fromBrother: ""
}),
methods: {
messageBrother() {
eventBus.$emit("sisterSaid", "妈妈说,该做作业了!(^_^)!!!");
}
},
created() {
eventBus.$on("brotherSaid", message => {
this.fromBrother = message;
});
}
};
</script>
<!-- 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="fromSister" class="alert" v-html="fromSister"></div>
</div>
</div>
</template>
<script>
import { eventBus } from "../main.js";
export default {
name: "BrotherCard",
data: () => ({
theCardTitle: "Brother Card",
fromSister: ""
}),
methods: {
messageSister() {
eventBus.$emit("brotherSaid", "妈妈说,该做作业了!(^_^)!!!");
}
},
created() {
eventBus.$on("sisterSaid", message => {
this.fromSister = message;
});
}
};
</script>