关于vue.js:Vue2兄弟组件通信

49次阅读

共计 782 个字符,预计需要花费 2 分钟才能阅读完成。

创立 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>

正文完
 0