VUE兄弟组件通信BUS总线

首先在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>

上一篇:EventBus 发送的消息,如何做到线程切换?,看完吊打面试官


下一篇:构造函数实现单例模式 观察者模式面试题