【发布时间】:2020-03-18 19:29:47
【问题描述】:
我有一个祖父组件、一个父组件和一个子组件。
问题:如果祖父将一个组件传递给子组件中的插槽,父组件可以插入数据吗?出现在孩子身上?
视觉上是这样的:
--------Grandparent -------------> Parent -------------> child------------>Slot
/|\ /|\ /|\
| | |
[Slot component identified ] | [Data added]| [data shows in slot component]
需要注意的是,父项是一个列表,子项是列表项。孩子们确实收到了插槽,但我无法让父母将个人 ID 传递给孩子们。
实际模板如下所示:
祖父(列表容器):
<template>
...
<KeywordList v-model="activeKeywordIds">
<KeywordDetailsEditContent slot="details" v-if="activity === 'editResumeContent'"/>
<template v-slot:details>
<KeywordDetails_Editing v-if="editing"/>
<KeywordDetails_PrivView v-if="viewing && loggedIn"/>
<KeywordDetails_PublicView v-else />
</template>
</KeywordList>
...
</template>
父(关键字列表):
<template>
...
<KeywordLI
v-for="keywordId of value"
:key="keywordId"
:str-keyword-id="keywordId"
>
<template v-slot:details>
<slot name="details"></slot>
</template>
</KeywordLI>
...
</template>
儿童(关键字LI):
<template>
...
<div
class="detailsContainer"
ref="detailsContainer"
v-if="appWidthDescription > 1"
>
<div ref="details" style="height: fit-content">
<slot name="details"></slot>
</div>
</div>
..
</template>
插槽组件
<template>
{{strKeywordId}} [Other computed/fetched details depending on which component was sent]
</template>
所以祖父母知道渲染什么细节,但是直到父组件才分解出细节,而子组件是它们需要聚集在一起的地方。
到目前为止,这还没有奏效:
- 在父组件的插槽中添加一个道具。
<template>
...
<KeywordList>
...
<KeywordLI
v-for="keywordId of value"
:key="keywordId"
:str-keyword-id="keywordId"
>
<template v-slot:details>
<slot name="details" :str-keyword-id='keywordId'></slot> //<----Adding prop to slot
</template>
</KeywordLI>
...
</KeywordList>
...
</template>
- 将 prop 添加到父模板中
<template>
...
<KeywordLI
v-for="keywordId of value"
:key="keywordId"
:str-keyword-id="keywordId"
>
<template v-slot:details :str-keyword-id='keywordId'> //<----Adding prop directly to slot
<slot name="details"></slot>
</template>
</KeywordLI>
...
</template>
【问题讨论】:
-
我很难按照这里的命名。子组件是
KeywordLI吗?父组件是KeywordList?祖父母模板和父模板似乎都包含KeywordList,我正在努力协调。我也无法弄清楚哪个组件“插槽组件”是。这是名称以KeywordDetails开头的组件之一吗? -
感谢您查看@skirtle-我输入的代码不正确。当前版本是正确的。回答您的问题:子组件是“KeywordLI”,父组件是“KeywordList”。 “插槽组件”是 KeywordDetails。因此,祖父母将知道哪些“KeywordDetails”是合适的,并将相应的组件发送到适当的 KeywordList 插槽,然后将其转发到适当的 KeywordLI 插槽。
标签: vue.js