[英]How to call component method from slot - 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>
如您所見,有一個方法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
,並在@click
上為每個li
使用它。 這可能嗎 ? 我會感謝任何幫助。 提前致謝。
以下代碼語法僅適用於 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
在您的子組件中,您將使用 scoped-slots 來訪問綁定的函數。
<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);
}
我希望這是有道理的 :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.