Vue全局事件總線



目標: 實現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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM