如何把兄弟组件 1 的内容传给 兄弟组件 2 ?html
例如
把子兄弟组件 1 的说的话传给兄弟组件 2 并在兄弟组件 2 上显示vue
思路
建立 eventHub
用来接收和发送事件
组件 1 在 被点击时发送事件至 eventHub
组件 2 在 created
时监听事件,当事件触发时调用处理函数
处理函数把组件 1 发送过来的数据在组件 2 内展现npm
<!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>