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>

 

發佈了24 篇原創文章 · 獲贊 12 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章