JSFiddle - React, Tailwind, and code Playground

by ChangJoo Park

HTML

<script src="https://unpkg.com/[email protected]/dist/vue.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Faker/3.1.0/faker.js"></script>

    <div id="app">
      <child-a></child-a>
      <child-b></child-b>
    </div>

    <template id="child-a">
      <div class="child">
        <button v-on:click="sendMessage">event to B</button>
        <div>
          <span>Message from B</span>
          <ul>
            <li v-for="log in logs">{{log}}</li>
          </ul>
        </div>
      </div>
    </template>
    <template id="child-b">
      <div class="child">
        <button v-on:click="sendMessage">event to A</button>
        <div>
          <span>Message from A</span>
          <ul>
            <li v-for="log in logs">{{log}}</li>
          </ul>
        </div>
      </div>
    </template>

CSS

.child {
  float: left;
  border: 1px solid tomato;
  max-width: 400px;
}

JavaScript

var bus = new Vue();



Vue.component('child-a', {
  template: '#child-a',
  mounted: function () {
    bus.$on('message-from-b', function (message) {
      this.logs.push(message);
    }.bind(this));
  },
  data: function () {
    return {
      logs: []
    }
  },
  methods: {
    sendMessage: function () {
      bus.$emit('message-from-a', faker.lorem.sentence() + new Date());
    }
  }
});

Vue.component('child-b', {
  template: '#child-b',
  mounted: function () {
    bus.$on('message-from-a', function (message) {
      this.logs.push(message);
    }.bind(this));
  },
  data: function () {
    return {
      logs: []
    }
  },
  methods: {
    sendMessage: function () {
      bus.$emit('message-from-b', faker.lorem.sentence() + new Date());
    }
  }
});
var app = new Vue({
  el: '#app'
});