非父组件通信

127 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="demo">
        <left-block></left-block>
        <!-- 要显示传入的数据就得吧B组件demo写出来 -->
        <right-block></right-block> 
    </div>

    <script>
        Vue.component('left-block',{
            //点击出发handle事件
            template:'<div><button @click="handle">左板块</button></div>',
            data:function(){
                return{
                    move:'左板块内容-碟中谍'
                }
            },
            //定义handle事件
            methods:{
                handle:function(){
                    //用过根组件的bus传数据  ('时间名',所传数据)  可以传多个参数
                    this.$root.bus.$emit('notice',this.move)
                }
            }
        })
        Vue.component('right-block',{
            template:'<div>B组件</div>',
            created:function(){
                // 实例创建的时候就监听notice事件 并拿到所传过来的数据  也是用过bus  穿几个参数就接收几个参数
                this.$root.bus.$on('notice',function(value){
                    alert(value)
                    console.log(value)
                })
            }
        })
        var app = new Vue({
            el: '#demo',
            data: {
                //根目录必须有的 bus对象
                bus:new Vue()
            }
        }) 
    </script>
</body>

</html>