在vue js中,如何使用通过插槽渲染的复选框来调用子组件方法

我有一个父级组件:

<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>
iCMS 回答:在vue js中,如何使用通过插槽渲染的复选框来调用子组件方法

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

本文链接:https://www.f2er.com/1610419.html

大家都在问