Vue 之兄弟組件通訊

如何把兄弟組件 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>
相關文章
相關標籤/搜索