如何从插槽调用组件方法 - Vue



我是 Vue 的新手,对 Vue slots有问题。我有这样的组件

<template>
<div class="dropDown__container">
  <div
    v-show="isOpened"
    class="dropDown__content"
    style="display:none;"
  >
    <slot />
    <div class="dropDown__container-flex">
      <span
        class="dropDown__button"
        @click="hideDropDown()"
      >
        Clear
      </span>
      <span
        class="dropDown__button"
        @click="hideDropDown(true)"
      >
        Submit
      </span>
    </div>
  </div>
</div>

如您所见,我想将一种方法

传递给我的slot hideDropdown。对于您的信息,我正在使用这样的slot

<drop-down>
<div class="d-flex flex-row justify-content-between">
    <ul id="priceFromList" class="hintList hintList--left">
        <li class="hintList__item" v-for="price in lessThan(autocompletePricesDesktop, editableCriteria.Price.To)" @click="">
            {{ price }}
        </li>
    </ul>
</div>
</drop-down>

我想要实现的是将hideDropdown方法从组件传递到slot,并在每个li@click上使用它。这可能吗?我会感谢任何帮助。提前谢谢。

下面的代码语法只能在 vue 2.6 中使用

好吧,你实际上可以实现它。我不确定这是否是最佳实践。以下是实现它的方法。

在你的父组件中将函数绑定到插槽 <slot :callableFunc="hideDropDown"/>

  <template>
    <div class="dropDown__container">
      <div
        v-show="isOpened"
        class="dropDown__content"
        style="display:none;"
      >
        <slot :callableFunc="hideDropDown"/>
        <div class="dropDown__container-flex">
          <span
            class="dropDown__button"
            @click="hideDropDown()"
          >
            Clear
          </span>
          <span
            class="dropDown__button"
            @click="hideDropDown(true)"
          >
            Submit
          </span>
        </div>
      </div>
    </div>
  </template

在子组件中,您将利用作用域槽来访问绑定函数。

<drop-down>
<template v-slot:default="{ callableFunc}">
<div class="d-flex flex-row justify-content-between">
    <ul id="priceFromList" class="hintList hintList--left">
        <li class="hintList__item" v-for="price in lessThan(autocompletePricesDesktop, editableCriteria.Price.To)" @click="callableFunc()">
            {{ price }}
        </li>
    </ul>
</div>
</template>
</drop-down>

请查看文档 https://v2.vuejs.org/v2/guide/components-slots.html#Scoped-Slots

我认为为了

分离关注点,下拉容器应该是决定何时关闭下拉列表的容器,并且插槽包含的组件应该发出一个事件,该事件可用于指示发生了某些事情,例如,已选择一项。

我会让容器侦听插槽上的事件: <slot v-on:item-selection="itemSelected" />

。以及接收所选值的函数:

function itemSelected(price) {
  this.price = price;
  hideDropdown();
}

在这种情况下,该事件称为 item-selection

然后我会向该事件发出包含的组件: <li class="hintList__item" v-for="price in lessThan(autocompletePricesDesktop, editableCriteria.Price.To)" @click="itemClicked(price)">

。以及该组件中的方法:

itemClicked(price) {
    this.$emit('item-selection', price);
}

我希望这是有道理的:-(

最新更新