在 vue js 中如何使用通过插槽呈现的复选框调用子组件方法

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

我有一个父组件:

<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>

在我的子组件中,我有方法,我需要在单击复选框时调用该方法以捕获复选框事件。

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

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

使用一个scoped slot传递方法:

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

然后你可以 destructure the slot prop 为传递的方法,并将其绑定到复选框的处理程序:

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

demo