【问题标题】:How to render another component's scoped slot?如何渲染另一个组件的作用域插槽?
【发布时间】:2020-05-02 16:24:24
【问题描述】:

最小的完整可验证示例

This CodeSandbox 是 MCVE。

问题描述

为了简要描述我的问题,我有以下无渲染组件的结构(全部使用作用域插槽并且只渲染其中的第一项):

  • FragmentA 用于在其中与 FragmentBs 一起使用
  • FragmentBFragmentCs 一起使用
  • FragmentC 将呈现其作用域插槽

问题在于,有时,根据某些输入,FragmentC 应该呈现 FragmentB

为了避免在用户空间模板中重复FragmentB 部分,我希望能够使用来自FragmentC 的输入数据在FragmentC 内呈现FragmentB 的作用域槽。

确保这种“递归”具有呈现FragmentC 自己的槽的基本情况。

到目前为止我已经尝试过什么

我尝试使用提供/注入 API 直接访问插槽,如何访问作用域本身可能不是问题,我相信它来了从我尝试渲染它的方式来看。

作为独生子渲染

// FragmentC.vue
{
  inject: ["$fragB"],
  components: { FragmentB },
  render(h){
    return /*some condition*/
    ? this.$scopedSlots.default(/* render own scoped slot */)[0]
    : h(
      FragmentB,
      {},
      this.$fragB.$scopedSlots.default(/* render FragmentB scoped slot */)[0]
    );
  }
}

这将导致递归渲染的FragmentBthis.$scopedSlots.default 不是函数。

渲染为子数组

// FragmentC.vue
{
  inject: ["$fragB"],
  components: { FragmentB },
    return /*some condition*/
    ? this.$scopedSlots.default(/* render own scoped slot */)[0]
    : [h(
      FragmentB,
      {},
      this.$fragB.$scopedSlots.default(/* render FragmentB scoped slot */)[0]
    )];
}

这将导致无限递归。

一句话中的具体问题

如何以编程方式在另一个组件内渲染另一个组件的作用域插槽?

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    经过一番挖掘和一些代码的摆弄,我发现以下解决方案可以正确渲染:

    // FragmentC.vue
    {
      inject: ["$fragB"],
      components: { FragmentB },
      render(h){
        return /*some condition*/
        ? this.$scopedSlots.default(/* render own scoped slot */)[0]
        : h(
          FragmentB,
          {
              props: {/*fragB props*/},
              scopedSlots: {
                  default: this.$fragB.$scopedSlots.default(/* render FragmentB scoped slot */)[0],
              }
          },
          [
              this.$fragB.$scopedSlots.default(/* render FragmentB scoped slot */)[0],
          ]
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 2013-01-20
      • 2020-06-03
      • 2021-07-28
      • 1970-01-01
      • 2019-03-07
      • 2020-12-26
      • 1970-01-01
      • 2020-11-15
      相关资源
      最近更新 更多