目标: 实现A向B通信

1. 确定全局事件总线: 将vm对象作为事件总线挂载到vue的原型对象上
	new Vue({
		beforeCreate () {
			Vue.prototype.$bus = this
		}
	})
2. A组件: 调用(分发)事件
	this.$bus.$emit('xxx', data)
3. B组件: 绑定事件监听
	this.$bus.$on('xxx', this.fn)
	
	methods{
		fn (data) {
			
		}
	}
功能: 实现任意组件间通信
  • 案例展示
    App.vue
<template>
    <div>
        <!-- <Child @myModel="myModel"/> -->
        <Child ref="myChild"/>
        <div>{{ChildMessage}}</div>
        <div>{{GlobalMessage}}</div>
    </div>
</template>
<script>
import Child from './components/Child.vue'
export default {
    name: "App",
    mounted() {
        this.$refs.myChild.$on("myModel",this.myModel);
        this.$bus.$on("global",this.global)
    },
    components:{
        Child
    },
    data(){
        return{
            ChildMessage:"~~~",
            GlobalMessage:"~~~"
        }
    },
    methods: {
        myModel(value){
            this.ChildMessage = this.ChildMessage+value
        },
        global(value){
            this.GlobalMessage = this.GlobalMessage + value
        }
    },
};
</script>
<style scoped>
</style>

Child.vue

<template>
    <div>
        <button @click="myM">自定义组件</button>
        <button @click="myG">全局事件组件</button>
    </div>
</template>
<script>
export default {
    name: "",
    methods: {
        myM(){
            this.$emit("myModel","子传父")
        },
        myG(){
            this.$bus.$emit("global","Global")
        }
    },
};
</script>
<style scoped>
</style>
posted on 2021-07-10 15:10  文种玉  阅读(1325)  评论(0编辑  收藏  举报