【问题标题】:Vue render function: include slots to child component without wrapperVue渲染功能:在没有包装器的情况下将插槽包含到子组件中
【发布时间】:2021-09-17 02:10:21
【问题描述】:

我正在尝试制作一个功能组件,它根据道具呈现一个或另一个组件。 其中一个输出必须是<v-select> 组件,我想将它传递给它的所有槽/道具,就像我们直接调用它一样。

<custom-component :loading="loading">
  <template #loading>
    <span>Loading...</span>
  </template>
</custom-component>

<!-- Should renders like this (sometimes) -->
<v-select :loading="loading">
  <template #loading>
    <span>Loading...</span>
  </template>
</v-select>

但是我无法找到一种方法来将分配给我的功能组件的插槽包含到我正在渲染的内容中,而无需在它们周围添加包装器:

render (h: CreateElement, context: RenderContext) {
  // Removed some logic here for clarity
  return h(
    'v-select', 
    {
      props: context.props,
      attrs: context.data.attrs,
      on: context.listeners,
    },
    [
      // I use the `slot` option to tell in which slot I want to render this.
      // But it forces me to add a div wrapper...
      h('div', { slot: 'loading' }, context.slots()['loading'])
    ],
  )
}

我不能使用scopedSlots 选项,因为这个插槽(例如)没有插槽道具,所以这个函数永远不会被调用。

return h(
  'v-select', 
  {
    props: context.props,
    attrs: context.data.attrs,
    on: context.listeners,
    scopedSlots: {
      loading(props) {
        // Never called because no props it passed to that slot
        return context.slots()['loading']
      }
    }
  },

有什么方法可以将插槽传递给我正在渲染的组件而不添加包装元素?

【问题讨论】:

    标签: vue.js vue-render-function


    【解决方案1】:

    我发现使用createElement 函数来渲染&lt;template&gt; 标签是完全有效的,同样用于确定我们在哪个插槽。

    所以像这样使用它可以解决我的问题:

    render (h: CreateElement, context: RenderContext) {
      // Removed some logic here for clarity
      return h(
        'v-select', 
        {
          props: context.props,
          attrs: context.data.attrs,
          on: context.listeners,
        },
        [
          // I use the `slot` option to tell in which slot I want to render this.
          // <template> vue pseudo element that won't be actually rendered in the end.
          h('template', { slot: 'loading' }, context.slots()['loading'])
        ],
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-03
      • 2019-09-28
      • 2017-09-19
      • 2018-11-26
      • 1970-01-01
      • 2021-04-16
      • 2017-02-27
      • 2021-07-28
      相关资源
      最近更新 更多