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

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.$emith传递数据

<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>
复制代码

转载于:https://juejin.im/post/5d06fe86e51d455071250b07

猜你喜欢

转载自blog.csdn.net/weixin_34059951/article/details/93176292