我是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上使用它。这是可能的吗?我会尽我所能帮助你。提前谢谢。
发布于 2019-03-29 22:25:15
以下代码语法仅在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://vuejs.org/v2/guide/components-slots.html#Scoped-Slots
发布于 2019-03-29 15:50:55
我认为为了分离关注点,dropdown-container应该决定何时关闭dropdown,而包含槽的组件应该发出一个事件,该事件可以用来指示发生了什么事情,例如,已经选择了一个项。
我会让容器监听插槽上的一个事件:<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);
}我希望这是合理的:-)
https://stackoverflow.com/questions/55412062
复制相似问题