Vuejs 用$emit与$on来进行兄弟组件之间的数据传输通信
LiuYier 人气:0最近在学习vue组件鸡组件之前通信问题,正好看到,以此来留作笔记。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Vue2-单一事件管理组件通信</title> <script src="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 () { 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 () { 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 () { 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><https://img.qb5200.com/download-x/dom-a> <dom-b><https://img.qb5200.com/download-x/dom-b> <dom-c><https://img.qb5200.com/download-x/dom-c> </div> </body> </html>
加载全部内容