How to call method or emit event to parent component from a slotted component? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to call method or emit event to parent component from a slotted component? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

This is my template

<template>
  <some-component>
    <button>Hello!</button>
  </some-component>
</template>

This is my component (some-component)

<template>
  <slot />
</template>

<script>
export default {
  methods: {
    someMethod() {
      // Does something
    }
  }
}
</script>

How would I go about calling someMethod() from the button that is slotted into the component, or otherwise, emit an event that some-component can listen to, to run the method itself from the button slotted in?

Answer

You could pass someMethod as a slot prop of some-component:

<template>
  <slot :onClick="someMethod" />
</template>

Then the parent that uses some-component could bind the slot prop to the button:

<some-component>
  <template v-slot="{ onClick }">
    <button @click="onClick">Click me</button>
  </template>
</some-component>

demo

We are here to answer your question about How to call method or emit event to parent component from a slotted component? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji