脚本宝典收集整理的这篇文章主要介绍了Vue 之兄弟组件通信,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。
如何把兄弟组件 1 的内容传给 兄弟组件 2 ?
例如
把子兄弟组件 1 的说的话传给兄弟组件 2 并在兄弟组件 2 上显示
思路
创建 eventHub
用来接收和发送事件
组件 1 在 被点击时发送事件至 eventHub
组件 2 在 created
时监听事件,当事件触发时调用处理函数
处理函数把组件 1 发送过来的数据在组件 2 内展示
<!DOCTYPE htML> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <tITle></title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.7/dist/vue.js"></script> </head> <body> <div id="app"> <brother1></brother1> <brother2></brother2> </div> </body> <script> let eventHub = new Vue() Vue.PRototype.$eventHub = eventHub Vue.component('brother1', { template: ` <div> brother1 <button v-on:click='say1'>say</button> </div> `, methods: { say1: function () { this.$eventHub.$emit('say', 'i am brother1') } } }) Vue.COMponent('brother2', { data: function () { return { message: '', } }, template: ` <div> brother2 hear: {{message}} </div> `, created() { this.$eventHub.$on('say',(data) => { this.message = data }) } }) new Vue({ el: '#app', }) </script> </html>
觉得可用,就经常来吧! 脚本宝典 欢迎评论哦! vue,巧夺天工,精雕玉琢。小宝典献丑了!
以上是脚本宝典为你收集整理的Vue 之兄弟组件通信全部内容,希望文章能够帮你解决Vue 之兄弟组件通信所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。