JSFiddle - React, Tailwind, and code Playground

by lid0

HTML

<template id="app-template"  >
<div class="app">
 <div>
  <b>App</b>
  </div>
  <div>
  Last Event: {{lastEvent}}
  </div>
  <my-comp></my-comp>
</div>
  
</template>

<template id="mycomp-template">
<div class="subComp">
   <div>
 Child <b @click="">A</b>
 </div>
  <my-comp-b></my-comp-b>
</div>

</template>

<template id="mycomp-b-template">
<div class="subComp">
Child B
<button @click="notifyParent('world')">click to emit directly to parent</button>
</div>

</template>


<pre>use provide/inject composition to emit event directly to parent for deep nested component child</pre>
<div id="app">

</div>

CSS

ul {
  float:left;
}

.app {
  border:1px solid gray;
}

.subComp {
  border:1px solid gray;margin-left:20px;padding:10px;display:inline-block
}

.subComp {
  border:1px solid gray;margin-left:20px;padding:10px;display:inline-block
}

JavaScript

// author: lidlanca March 31
import {createApp,defineComponent,provide, inject,ref} from "https://unpkg.com/[email protected]/dist/vue.esm-browser.js";

var myCompB = defineComponent( {
name:"my-compb",
template: "#mycomp-b-template",
setup(){

	return {
   notifyParent: inject('notifyParent')
  }
}
})


var myComp = defineComponent( {
name:"my-comp",
template: "#mycomp-template",

components:{
    myCompB
  }
})





const app = createApp({
	template:"#app-template",
  
  setup() {
  const lastEvent = ref("hello")
  	function notifyParent(message){
       lastEvent.value  +=  " "  + message
    }
		provide('notifyParent', notifyParent)
    return {
       notifyParent,
       lastEvent
    }
	},
  
  components:{
  	myComp,
    myCompB
  }
});

app.mount("#app");