vuejs - 向下传递范围模板多个 child-levels

vuejs - pass scope templates down multiple child-levels

我正在用 vue 构建一个 table,我使用插槽来自定义格式。 F.e。 table(它是一个组件),使用一个 thead-组件,其中每个 th 是一个 scoped/named-slot。尽管为插槽指定模板仅适用于 parent 到 child(或者看起来 - vm.$scopedSlots 对于 thead 组件是空的)。

这是它的轮廓:

// in index.html
<my-table :data="data">
  <template name="col1-header" props="column">
    <th style="colour: blue;">{{ column.name }}</th>
  </template>
</my-table

// in my-table component
<template>
  <table>
    <my-thead :columns="columns">
    </my-thead>
    // tr: v-for over data
  </table>
</template>

// in my-thead component
<template>
  <thead>
    <tr>
      <slot :name="column.name + '-header'" :item="column" v-for="column in columns">
        <th>{{ column.name }}</th>
      </slot>
    </tr>
  </thead
</template>

使用 template 没有用,因为它似乎只适用于 my-table 而不是 my-thead。使用 my-thead 中定义的 slot 的唯一方法是在 my-table 组件中添加模板,但我需要在组件外部指定它们。

有没有办法将使用 my-table 时指定的模板传递给 my-thead 组件?正如我已经提到的,我尝试使用 vm.$scopedSlots,但是这个 属性 是 read-only 并且不能在 my-thead 组件上设置。不过,我可以访问 parent vm$scopedSlots。我还尝试在 my-table 组件中使用 slottemplate 以某种方式将模板传递给 child,但这也没有用。

我不得不为这个问题创建一个 github issue。根据评论,有多种处理方法:

将插槽传递给 child,方法是使用渲染函数,如下所示,并设置 scopedSlot 属性,或者使用 属性 来传scopedSlots,如图here。或者使用 2.2.0 版本添加的 provide/inject 机制来设置 scopedSlots(我还没有尝试过)。

render (h) {
  return h('child', {
    scopedSlots: this.$scopedSlots
  })
}