JSFiddle - React, Tailwind, and code Playground

by robert chang

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.0-rc.4/vue.js"></script>
<div id="app">
  <pcom id=1>
    <soncom msg="Foo"></soncom>
  </pcom>
  <pcom id=2>
    <soncom msg="Bar">
      <soncom msg="Nested"></soncom>
    </soncom>
  </pcom>
</div>

Babel + JSX

const Mixin = {
	computed: {
  	pcomBus () {
    	let target = this
      while (target && !target._bus) {
      	target = target.$parent
      }
      if (!target) {
      	throw new Error('should have event bus on ancestor')
      }
      return target._bus
    }
  }
}

const Pcom = {
	template: '<div><slot></slot></div>',
	beforeCreate () {
  	this._bus = new Vue()
    this._bus.$on('message', msg => {
    	alert(`Pcom id=${this.$el.id}, msg=${msg}`)
    })
  }
}

const Soncom = {
	mixins: [Mixin],

  props: ['msg']  ,
  template: `<div>
  	<button @click="send">Send Message: {{ msg }}</button>
    <slot></slot>
  </div>`,
  methods: {
  	send () {
    	this.pcomBus.$emit('message', this.msg)
    }
  }
}

new Vue({
	el: '#app',
  components: {
  	Pcom,
    Soncom
  }
})