创建 eventHub
兄组件向 eventHub 发送数据
弟组件监听 eventHub 获取数据
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <div>
      <myinput @add="add" />
    </div>
    <div>
      <mylist/>
    </div>
  </div>
</body>
<script>
  const eventHub = new Vue()
  Vue.prototype.$eventHub = eventHub
  // 
  Vue.component('myinput', {
    template: `
      <div>
        <input v-model="title">
        <button @click="add"> add </button>
      </div>
    `,
    data() {
      return {
        title: '',
      }
    },
    methods: {
      add() {
        this.$eventHub.$emit('add', this.title)
      }
    }
  })
  Vue.component('mylist', {
    template: `
      <ul>
        <li v-for="item in list" :key="item.id">
          {{ item.title }}
        </li>
      </ul>
    `,
    data: function() {
      return {
        list: []
      }
    },
    created() {
      this.$eventHub.$on('add', (title) => {
        this.list.push({
          id: Math.random(),
          title,
        })
      })
    }
  })
  // 
  var app = new Vue({
    el: '#app',
  })
</script>
</html>

TaoWu
15 声望2 粉丝