首页 > 解决方案 > 将插槽传递给插槽

问题描述

我正在构建一个小型库,它允许从其他组件中修改应用程序布局的一部分。

基本思想是拥有一个主要的导航组件:

<template>
  <div class='main-navigation>
    <div class='logo'><img...>
    <div class='actions'>
      <Container name='extra-actions' />
      <a href="some-action">Action</a>
    </div>
</template>

然后组件可以注册其他内容:

<template>
  <div class='home-page'>
    <ContentFor container="extra-actions">
      <a href='some-home-specific-action'>Do sth extra</a>
    </ContentFor>

    ...rest of the page
  </div>
</template>

我已经设法使上述工作正常工作,使用自定义插件和服务对象将插槽注册(和更新)为 ContentFor 中定义的 VNode 并将其呈现在容器中。我现在想通过允许用户根据给定的内容添加自定义布局来增强它,例如:

<ul class='actions'>
  <Container name='extra-actions'>
    <li><slot></slot></li>
  </Container>
</ul>

这将很好地将视图组件与导航结构分离。我尝试了以下方法:

render (h) {
  return h(Fragment, Object.values(this.contents).map((content) => {
    if (this.$scopedSlots.default) {
      return this.$scopedSlots.default({
        slots: { default: content.slot } # this does nothing!
      })
    } else {
      # This works as expected
      return content.slot
    }
  }))
},

当没有自定义模板时,上述工作正常。当存在自定义模板时,它会呈现该模板,但不会将内容传递到模板的插槽,从而导致:

<ul class='actions'>
  <li></li> # instead of <li><a href='some-home-specific-action'>Do sth extra</a></li>
</ul>

是否有任何特定的方式可以将范围传递给其他范围?

标签: vuejs2vue-componentvuejs-slots

解决方案


因此,在反复进行此操作后,我了解到这是不可能用插槽解决我的模板问题的。当我做

# layout/Navigation.vue
<ul>
  <Container name='main-nav-actions>
    <li><slot/></li>
  </Container>
</ul>

</slot>正在导航组件的上下文中解决 - 这意味着此时它是 VNode 的静态数组。因此,插槽不能拥有自己的动态嵌套插槽。

相反,我必须编写一个负责渲染 VNode 的功能组件:

export {
  name: 'RenderContent',
  functional: true,
  render (h, { props }) { return props.content }
}

暴露后,我现在可以使用 scopedSlot 构建我的模板:

  <Container name='main-nav-actions vue-slot="{ content }">
    <li><RenderContent :content="content"></li>
  </Container>

这不是最漂亮的解决方案,但它似乎有效,允许通过 ContentFor 传递可选选项,这非常棒。


推荐阅读