1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>兄弟组件之间数据交互</title> 9 </head> 10 11 <body> 12 <div id="app"> 13 <div>父组件</div> 14 <div> 15 <button @click='handle'>销毁事件</button> 16 </div> 17 <test-tom></test-tom> 18 <test-jerry></test-jerry> 19 </div> 20 </body> 21 <script src="../js/vue.js"></script> 22 <script> 23 //提供事件中心 24 var hub = new Vue(); 25 26 Vue.component('test-tom', { 27 data: function () { 28 return { 29 num: 0 30 } 31 }, 32 template: ` 33 <div> 34 <div>TOM:{{num}}</div> 35 <div> 36 <button @click='handle'>点击</button> 37 </div> 38 </div> 39 `, 40 methods: { 41 handle: function () { 42 //传递数据方,通过一个事件触发hub.$emit(方法名,传递的数据) 43 hub.$emit('jerry-event', 2); 44 } 45 }, 46 mounted: function () { 47 // 监听事件 48 //接收数据方,通过mounted(){} 钩子中 触发hub.$on()方法名 49 hub.$on('tom-event', (val) => { 50 this.num += val; 51 }); 52 } 53 }); 54 55 Vue.component('test-jerry', { 56 data: function () { 57 return { 58 num: 0 59 } 60 }, 61 template: ` 62 <div> 63 <div>JERRY:{{num}}</div> 64 <div> 65 <button @click='handle'>点击</button> 66 </div> 67 </div> 68 `, 69 methods: { 70 handle: function () { 71 // 触发兄弟组件的事件 72 hub.$emit('tom-event', 1); 73 } 74 }, 75 mounted: function () { 76 // 监听事件 77 hub.$on('jerry-event', (val) => { 78 this.num += val; 79 }); 80 } 81 }); 82 83 var vm = new Vue({ 84 el: "#app", 85 data: { 86 87 }, 88 methods: { 89 handle: function () { 90 hub.$off('tom-event'); 91 hub.$off('jerry-event'); 92 } 93 } 94 }); 95 </script> 96 97 </html>