Vue非父子组件间的通信(bus中央事件总线)

287 阅读1分钟

Main.js

首先在Main.js中创建中央事件总线bus

Vue.prototype.bus = new Vue()

父组件

<template>
    <child1></child1>
    <child2></child2>
</tempalte>

<script>
    import childComponent from './components/child1'
    import childComponent from './components/child2'
    export default(){
        name:'App',
        components:{
            child1,
            child2
        }
    }
</script>

组件1

通过this.bus.$emit传递数据

<template>
   <h1 @click="ch1">{{child1msg}}</h1>
</tempalte>

<script>
    export default(){
        name:'child1',
        data(){
            return{
                child1msg:'我是组件1的数据'
                
            }
        },
        methods:{
            ch1(){
                this.bus.$emit('message',this.child1msg)
            }
        }
        
    }
</script>

组件2

在生命周期函数created或者mounted中获取 通过this.bus.$on('message',function(res){ console.log(res) //res就是组件1传过来的值 })

<template>
   <h1 @click="ch2">{{child2msg}}</h1>
</tempalte>

<script>
    export default(){
        name:'child2',
        data(){
            return{
                child2msg:'我是组件1的数据'
                
            }
        },
        created(){
            let _this = this
            this.bus.$on('message',function(res){
                _this.child1msg = res
            })
        }
        
    }
</script>