JSFiddle - React, Tailwind, and code Playground

by lid0

HTML

<h3>
Incrementor/Counter - provide to child via prop. (v 2)
</h3>
<div id="app">
Parent: {{parentCounter}}
<child-component  :incrementor="parentInc"></child-component>
</div>

Vue

// author: lidlanca 2021 april 4

// passing an incrementor, which is used by the child to increment or decrement a counter.
// or show the counter value.

// child component
Vue.component('child-component', {
    props: ["counter","incrementor"],
    template: `
        <div>
        Child: 
            {{incrementor()}}
            <button @click="()=>this.incrementor(1)">Inc</button>
            <button @click="()=>this.incrementor(-1)">Dec</button>
        </div>`
}
)

// app
new Vue({
  el: "#app",
  data() {
    return {
      parentCounter: 0
    }
  },
  methods:{
  	parentInc(by){
       if(by == undefined) return this.parentCounter; // return counter when no arguments.
                                                      // note that if this is called in child, it will provide the actual reference
                                                      // not readonly, if read only is implemented for a props.
                                                      // so there will be no warnnings in dev mode, if mutating in child.
       this.parentCounter+=by;
       if( this.parentCounter < 0 ) this.parentCounter=0
       if( this.parentCounter >10 ) this.parentCounter=10
    }
  }
  
})