【问题标题】:Passing slot to grandchild though dynamic component通过动态组件将插槽传递给孙子
【发布时间】:2021-09-21 16:26:15
【问题描述】:

我有一个包装器组件(Wrapper.vue)。

<component v-for="c of comps" :key="c.componentName" :is="c.componentName">
      <slot :name="c.componentName">
      </slot>
</component>

const comps = 
      [
        {
          componentName: "Child1",
        },
        {
          componentName: "Child2",
        }
      ];

Child1.vue 如下所示

<template>
  <div class="hello">
    <slot name="top">Child1 slot top text</slot>
  </div>
</template>

Child2.vue 如下所示

<template>
  <div class="hello">
    <slot name="top">Child2 slot top text</slot>
  </div>
</template>

我想在 App.vue

中使用如下包装器
<Wrapper>
      <template slot="slot1">
        <template slot="top">Inner Content1</template>
      </template>
      <template slot="slot2">
        <template slot="top">Inner Content2</template>
      </template>
</Wrapper>

CodeSandbox 链接:- https://codesandbox.io/s/mystifying-burnell-ir8un

它显示来自 Child1 和 Child2 而不是 App.vue 的默认文本 应该怎么解决?

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    我更改了一些代码,这就是结果。我所做的更改:

    • 你已经在 App.vue 中嵌套了 &lt;template&gt; 标签。
    • 包装器本身需要有一个名为“top”的插槽模板,并且在此模板中我添加了一个与组件同名的插槽

    https://codesandbox.io/s/lucid-smoke-uzgn7?file=/src/App.vue

    【讨论】:

    • 你能再检查一下沙箱吗?我认为编辑访问权以某种方式被撤销。如果我删除 c.componentName 则所有传递的模板都将传递给每个组件,这将导致重复输出。我只想显示每个孩子必要的顶部位置。
    • 查看我的更新答案,我更改了代码,使其按预期工作。
    • 子组件中可能有多个插槽,如顶部、右侧、左侧、底部。而且我还想保持包装器独立(清洁)子组件中可用的插槽。
    • 我认为我的解决方案回答了最初的问题。
    猜你喜欢
    • 2019-04-25
    • 1970-01-01
    • 2018-09-14
    • 2020-10-08
    • 2017-12-06
    • 2018-08-19
    • 2020-04-23
    • 1970-01-01
    • 2021-07-11
    相关资源
    最近更新 更多