Vue中组件间的通信技巧

  • 在Vue中经常会遇到一些比较复杂的业务场景,需要组件之间隔代通信或者是兄弟组件之间相互通信,这种情况下,我们一般选用EventBus方式解决组件间的通信问题,具体实现如下:
// utils/EventBus.js
import Vue from 'vue';

// 直接导出一个Vue实例,使用Vue示例的$emit、$on、$once、$off的功能进行组件间的通信,由于所有的组件都引入同一实例,故相互间的通信是可以被彼此捕获的
export default new Vue();
// main.js
import Vue from "vue";
import App from "./App.vue";
import bus from "./utils/EventBus";

Vue.prototype.$bus = bus;


new Vue({
  render: h => h(App)
}).$mount("#app");
// a.vue
<template>
    <div class="container">
        
    </div>
</template>

<script>
    export default {
        name: "test",
        data(){
            return {
                userInfo:{}
            }
        },
        created(){
            this.$bus.$emit("aCreated",{message: "A had been created"});
            this.$bus.$on("bReceived",({message})=>{
                console.log("B had been received message from A,the message content is "+message);
            });
        }
    }
</script>

<style scoped>

</style>
//b.vue
<template>
    <div class="container">
        
    </div>
</template>

<script>
    export default {
        name: "test",
        data(){
            return {
                userInfo:{}
            }
        },
        created(){
            this.$bus.$emit("bCreated",{message: "B had been created"});
            this.$bus.$on("aCreated",({message})=>{
                this.$bus.$emit("bReceived",{message});
            });
        }
    }
</script>

<style scoped>

</style>
发布了32 篇原创文章 · 获赞 16 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/u010651383/article/details/103935586