【发布时间】:2020-05-02 16:24:24
【问题描述】:
最小的完整可验证示例
This CodeSandbox 是 MCVE。
问题描述
为了简要描述我的问题,我有以下无渲染组件的结构(全部使用作用域插槽并且只渲染其中的第一项):
-
FragmentA用于在其中与FragmentBs 一起使用 -
FragmentB与FragmentCs 一起使用 -
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]
);
}
}
这将导致递归渲染的FragmentB 和this.$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]
)];
}
这将导致无限递归。
一句话中的具体问题
如何以编程方式在另一个组件内渲染另一个组件的作用域插槽?
【问题讨论】: