首页 > 其他 > 详细

非父子组件的数据交换

时间:2020-06-30 21:09:48      阅读:43      评论:0      收藏:0      [点我收藏+]

使用一个新的vue实例hub作为事件中心

使用$emit发送事件,hub.$on()接受发送出来的事件

  //提供事件中心
        var hub = new Vue()
        
        let app = new Vue({
            el : ‘#app‘,
            data:{
              masssage:0  
            },
            components:{
                ‘cpn1‘ : {
                    data(){
                        return {
                            msg :2
                        }
                    },
                    template:`
                    <div>
                        juery:{{msg}}
                        <button @click = ‘juery‘>+</button>    
                    </div>
                    `,
                    methods:{
                        juery:function(){
                            hub.$emit(‘tom-click‘,1)
                        }
                    },
                    mounted:function(){
                        hub.$on(‘juery-click‘,(val)=>{
                           this.msg += val
                        })
                    }
                },
                ‘cpn2‘ : {
                    data(){
                        return {
                            mcount :0
                        }
                    },
                    template:`
                    <div>
                        tom:{{mcount}}
                        <button @click = ‘tom‘>+</button>    
                    </div>
                    `,
                    methods:{
                        tom:function(){
                        //点击之后发送事件
                        hub.$emit(‘juery-click‘,2)
                        }
                    },
                    mounted:function(){
                        //事件监听
                       hub.$on(‘tom-click‘,(val)=>{
                           //接受兄弟组件发送出来的事件
                        this.mcount += val
                       }) 
                    }
                },
                },
            methods:{
                destory:function(){
            //$off用于销毁事件,多个事件用数组表示 hub.$off([
‘juery‘,‘tom-click‘]) } } }) </script>

 

非父子组件的数据交换

原文:https://www.cnblogs.com/libainian/p/13215809.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!