vue 组件传值踩坑日记 2
Posted llcdbk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue 组件传值踩坑日记 2相关的知识,希望对你有一定的参考价值。
这里介绍一下适合兄弟组件和父子,祖孙组件之间的传值方式-事件总线,废话不多说,直接上代码
总结:说白了这东西就是一种发布订阅的模式,发数据的一方用$emit发,各个接听方用$on接受对应key的事件,on的时候,就选择在DOM挂在完毕以后进行监听,通过这样的事件去修改数据,完成传递工作,感兴趣的同学可以吧这个代码拿下去直接调试运行一下看看
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <div id="app"> <com1></com1> </div> <template id="com1"> <div> <h1>我是父组件</h1> <span>我接受孙组件的数据:{{msg}}</span> <input type="text" ref="txtMsg" v-model="msg" /> <com2></com2> <com3></com3> </div> </template> <template id="com2"> <div> <h3>我是兄弟组件2</h3> <button @click="SendMsg"> 发送到兄弟组件3 </button> <span> 我要接受兄弟组件com3的值:{{receiveTitle}},{{receiveMsg}} </span> </div> </template> <template id="com3"> <div> <h3>我是兄弟组件3</h3> <button @click="sendMsg"> 发送到兄弟组件2 </button> <span> 我要接受兄弟组件com2的值:{{receiveTitle}},{{receiveMsg}} </span> <com4></com4> </div> </template> <template id="com4"> <div> <h5>我是孙组件</h5> <span> 我要接受来自祖组件com1的值:{{sunMsg}} 我要改变祖组件的值 <input type="text" ref="txtMsg" v-model="sunMsg" /> </span> </div> </template> <script src="/lib/vue/vue.js"></script> <script type="text/javascript"> var eventBus = new Vue(); var com4 = { name: "com4", template: "#com4", data() { return { sunMsg: "" }; }, watch: { sunMsg() { eventBus.$emit("SetGrandFatherMsg", this.sunMsg); } }, mounted() { eventBus.$on("SetSunMsg", msg => { //console.log(msg); this.sunMsg = msg; }); } }; var com2 = { name: "com2", template: "#com2", data() { return { com2Title: "你好", com2Msg: "这是来自com2的消息", receiveTitle: "", receiveMsg: "" }; }, mounted() { eventBus.$on("SendCom2Msg", (title, msg) => { this.receiveMsg = msg; this.receiveTitle = title; }); }, methods: { SendMsg() { eventBus.$emit("SendCom3Msg", this.com2Title, this.com2Msg); } } }; var com3 = { name: "com3", template: "#com3", data() { return { com3Title: "hello", com3Msg: "This is the message from to COM3", receiveTitle: "", receiveMsg: "" }; }, mounted() { eventBus.$on("SendCom3Msg", (title, msg) => { this.receiveMsg = msg; this.receiveTitle = title; }); }, components: { com4 }, methods: { sendMsg() { eventBus.$emit("SendCom2Msg", this.com3Title, this.com3Msg); } } }; var com1 = { name: "com1", template: "#com1", data() { return { msg: "" }; }, mounted() { eventBus.$on("SetGrandFatherMsg", msg => { this.msg = msg; }); }, watch: { msg: { handler: function(newVal, oldVal) { console.log(this.msg); eventBus.$emit("SetSunMsg", this.msg); } } }, components: { com2, com3 } }; new Vue({ el: "#app", components: { com1 } }); </script> </body> </html>
以上是关于vue 组件传值踩坑日记 2的主要内容,如果未能解决你的问题,请参考以下文章
Vue 踩坑日记二:View UI 组件添加单击事件不生效问题