vue子组件作为slot如何调用父组件的方法并传值?

最近想实现一个checkbox组件,遇到了这个问题。大家看看我的代码,怎样才可以触发checkboxGroup的pushItem方法并拿到值。将@pushItem事件绑定到父元素没有作用。谢谢!

<checkbox-group  v-model="checkList">
        <check-box
          v-for="(item,index) in data"
          v-bind:key="index"
          :label="item.name"
          :value="item.id"
        ></check-box>
</checkbox-group>

CheckboxGroup.vue

<template>
  <div class="checkbox-group-wrap" ref="checkboxGroup">
    <slot></slot>
  </div>
</template>
<script lang='ts'>
import { Component, Vue, Watch, Prop } from "vue-property-decorator";
@Component({
  components: {}
})
export default class extends Vue {
  private checkBoxGroup: string[] = ["2", "3"];
  private pushItem(value) {
    this.checkBoxGroup.push(value);
    this.$emit("input", this.checkBoxGroup);
  }
  private removeItem(value) {
    const index = this.checkBoxGroup.indexOf(value);
    this.checkBoxGroup.splice(index, 1);
    this.$emit("input", this.checkBoxGroup);
  }
}
</script>
<style scoped lang="scss">
</style>

CheckBox.vue

<template>
  <div class="checkbox-wrap" @click="handleClick">
    <div class="left" :class="isChecked?'box-click':''" ref="box">
      <transition name="fade">
        <div class="hook" v-show="isChecked"></div>
      </transition>
    </div>
    <div class="right">{{label}}</div>
  </div>
</template>
<script lang='ts'>
import { Component, Vue, Watch, Prop } from "vue-property-decorator";
@Component({
  components: {}
})
export default class extends Vue {
  private isChecked: boolean = false;
  @Prop()
  private label!: string;
  @Prop()
  private value!: string;
  private handleClick() {
    if (!this.isChecked) {
      this.$emit("pushItem", this.value);
    } else {
      this.$emit("removeItem", this.value);
    }
    this.isChecked = !this.isChecked;
  }
}
</script>
阅读 6.6k
1 个回答

checkboxGroup.vue

private created() {
    this.$on("pushItem", this.pushItem);
    this.$on("removeItem", this.removeItem);
  }

Checkbox.vue

private handleClick() {
    if (!this.isChecked) {
      this.$parent.$emit("pushItem", this.value);
    } else {
      this.$parent.$emit("removeItem", this.value);
    }
    this.isChecked = !this.isChecked;
    this.$emit("input", this.isChecked);
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题