使用一个新的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