Aathira
Aathira

Reputation: 813

In vue js how to call child component method using check box rendered via slot

I have a parent component:

<my-component>
  <template v-slot:myslot>
    <b-form-group
       label="SlotEG"
       label-for="sltLbl"
       label-class="font-weight-bold pt-0"
    >
      <b-form-checkbox
        :id="myId"
        :name="myName"
      ></b-form-checkbox>
    </b-form-group>
  </template>
<my-component>

Here in my child component I have method and I need to call that method while clicking on the check box to capture the checkbox event.

<template>
  <b-col cols="3" v-if="hasMySlot()">
    <slot name="myslot"></slot>
  </b-col>
</template>

<script>
export default {
  methods:{
    myMethod() {
      alert("Hi")
    }
  }
}
</script>

Upvotes: 1

Views: 1224

Answers (1)

tony19
tony19

Reputation: 138336

Use a scoped slot to pass the method:

<!-- MyComponent -->
<slot name="myslot" :myMethod="myMethod" />

Then you could destructure the slot prop for the passed method, and bind it to the checkbox's handler:

<!-- Parent -->
<my-component>
  <template v-slot:myslot="{ myMethod }">
    ...
    <b-form-checkbox @checked="myMethod" />
  </template>
</my-component>

demo

Upvotes: 2

Related Questions