Vue兄弟组件之间通信

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/vue.js"></script>
</head>
<body>
    <div id="app">
         <child-1></child-1>
         <child-2></child-2>
    </div>
    <script>
        //1.创建公共的vue对象
        var bridge = new Vue();

        //2.创建两个兄弟组件
        Vue.component('child-1',{
            template:`
            <div>
                <input type="button" value="1->2" @click="sendData"/>
            </div>
            `,
            methods:{
                sendData:function(){
                    bridge.$emit('OneToTwoEvent','Hello 2, I am 1');
                }
            }
        });

        Vue.component('child-2',{
            template:`
            <div>
                <h4>{{msg}}</h4>
            </div>
            `,
            data:function(){
                return {
                    msg:''
                }
            },
            mounted:function(){
                bridge.$on('OneToTwoEvent',function(msg){
                    console.log('收到来自1的:'+msg);
                    this.msg=msg;
                })
            }
        })
        



        var vm = new Vue({
            el:"#app"
        })
    </script>
 
</body>
</html>

  

 

posted @ 2021-02-26 16:30  田野与天  阅读(681)  评论(0编辑  收藏  举报