Sarvar Nishonboyev
Sarvar Nishonboyev

Reputation: 13080

How to trigger the method on parent component from child using render function in Vuejs 3

How to trigger the clicked method on app2 from ComponentA in this example.

const app = Vue.createApp({});

app.component('ComponentA', {
    template: `<button @click="clicked" class='btn'>Click</button>`
});

const app2 = Vue.createApp({
   methods: {
     clicked() {
        this.clickCount += 1;
     }
   },

   render() {
     return Vue.h(app.component('ComponentA'), options);
   }
}).mount("#App");
            

Upvotes: 1

Views: 85

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

From the button click event handler try to emit an event called clicked, in render function define it by prefixing it by on and upper casing the first letter like onClicked: (e) => {...} inside the body of this function run this.clicked

let options = {}
options.baseUrl = "someurl.com";

const app = Vue.createApp({})
app.component('ComponentA', {
  template: `
        <button @click="$emit('clicked')" class='btn'>Click</button>
    `
});

const app2 = Vue.createApp({
  methods: {
    clicked() {
      console.log("clicked !!!")
      this.clickCount += 1;
    }
  },
  render() {
    return Vue.h(app.component('ComponentA'), {
      onClicked: (e) => {

        this.clicked()
      }
    }, options)
  }
}).mount("#app");
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>

<div id="app" someVariable='some value'>


</div>

Upvotes: 1

Related Questions