1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <title>Vue2-单一事件管理组件通信</title> 6 <script src="vue.js"></script> 7 <script type="text/javascript"> 8 9 //准备一个空的实例对象 10 var Event = new Vue(); 11 12 //组件A 13 var A = { 14 template: ` 15 <div> 16 <span>我是A组件的数据->{{a}}</span> 17 <input type="button" value="把A数据传给C" @click = "send"> 18 </div> 19 `, 20 methods: { 21 send () { 22 Event.$emit("a-msg", this.a); 23 } 24 }, 25 data () { 26 return { 27 a: "我是a组件中数据" 28 } 29 } 30 }; 31 //组件B 32 var B = { 33 template: ` 34 <div> 35 <span>我是B组件的数据->{{a}}</span> 36 <input type="button" value="把B数据传给C" @click = "send"> 37 </div> 38 `, 39 methods: { 40 send () { 41 Event.$emit("b-msg", this.a); 42 } 43 }, 44 data () { 45 return { 46 a: "我是b组件中数据" 47 } 48 } 49 }; 50 //组件C 51 var C = { 52 template: ` 53 <div> 54 <h3>我是C组件</h3> 55 <span>接收过来A的数据为: {{a}}</span> 56 <br> 57 <span>接收过来B的数据为: {{b}}</span> 58 </div> 59 `, 60 mounted () { 61 //接收A组件的数据 62 Event.$on("a-msg", function (a) { 63 this.a = a; 64 }.bind(this)); 65 66 //接收B组件的数据 67 Event.$on("b-msg", function (a) { 68 this.b = a; 69 }.bind(this)); 70 }, 71 data () { 72 return { 73 a: "", 74 b: "" 75 } 76 } 77 }; 78 window.onload = function () { 79 new Vue({ 80 el: "#box", 81 components: { 82 "dom-a": A, 83 "dom-b": B, 84 "dom-c": C 85 } 86 }); 87 }; 88 89 90 </script> 91 </head> 92 <body> 93 <div id="box"> 94 <dom-a></dom-a> 95 <dom-b></dom-b> 96 <dom-c></dom-c> 97 </div> 98 99 </body> 100 </html>