Vuejs 用$emit与$on来进行兄弟组件之间的数据传输通信
最近在学习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></dom-a> <dom-b></dom-b> <dom-c></dom-c> </div> </body> </html>
相关推荐
yuzhu 2020-11-16
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
sjcheck 2020-11-03
怪我瞎 2020-10-28
源码zanqunet 2020-10-28
gloria0 2020-10-26
王军强 2020-10-21
学习web前端 2020-09-28
QiaoranC 2020-09-25
anchongnanzi 2020-09-21
安卓猴 2020-09-12
Macuroon 2020-09-11
kiven 2020-09-11
LittleCoder 2020-09-11
Cheetahcubs 2020-09-13
小焊猪web前端 2020-09-10
颤抖吧腿子 2020-09-04
softwear 2020-08-21