我是 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>
如您所见,有一个方法 hideDropdown
,我想将其传递到我的 slot
。为了您的信息,我正在使用这个 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
上使用它
最佳答案
The below code syntax is only useable from vue 2.6
好吧,您实际上可以实现它。我不确定这是否是最佳做法。这是实现它的方法。
在你的父组件中将函数绑定(bind)到插槽
<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
在您的子组件中,您将使用作用域插槽来访问绑定(bind)函数。
<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
关于javascript - 如何从插槽中调用组件方法 - Vue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55412062/