<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Vue2-單一事件管理組件通訊</title> <script src="../lib/vue.js"></script> <script type="text/javascript"> //準備一個空的實例對象 var Event = new Vue(); //組件A var A = { template: '<div><span>我是A組件的數據->{{a}}</span><input type="button" value="把A數據傳給C" @click = "send"> </div>', methods: { send () { Event.$emit("a-msg", this.a); } }, data:function(){ return { a: "我是a組件中數據" } } }; //組件B var B = { template: '<div><span>我是B組件的數據->{{a}}</span><input type="button" value="把B數據傳給C" @click = "send"></div>', methods: { send () { Event.$emit("b-msg", this.a); } }, data:function(){ return { a: "我是b組件中數據" } } }; //組件C var C = { template: '<div><h3>我是C組件</h3><span>接收過來A的數據爲: {{a}}</span><br><span>接收過來B的數據爲: {{b}}</span></div>', mounted () { //接收A組件的數據 Event.$on("a-msg", function (a) { this.a = a; }.bind(this)); //接收B組件的數據 Event.$on("b-msg", function (a) { this.b = a; }.bind(this)); }, data:function(){ return { a: "", b: "" } } }; window.onload = function () { new Vue({ el: "#box", components: { "dom-a": A, "dom-b": B, "dom-c": C } }); }; </script> </head> <body> <div id="box"> <dom-a></dom-a> <dom-b></dom-b> <dom-c></dom-c> </div> </body> </html>
效果圖:javascript