代码之家  ›  专栏  ›  技术社区  ›  Jérôme

在grand child组件中使用命名插槽

  •  1
  • Jérôme  · 技术社区  · 7 年前

    我创建了一个全局组件,扩展了Bootstrap Vue表组件,为每个名为 VTable .

    <template>
      <div>
        <b-table
          :items="items"
          :fields="fields"
          ...
        >
        </b-table>
      </div>
    </template>
    
    <script>
      import Table from 'bootstrap-vue/es/components/table/table';
    
      export default {
        name: 'Vtable',
        extends: Table,
        ...
      };
    </script>
    

    我在另一个使用新的自定义HTML标记的组件中使用全局表组件。

    <v-table
      v-if="items"
      :items="items"
      :fields="fields"
      ...
    >
      <template
        slot="timestamp"
        slot-scope="data"
      >
        ...
      </template>
      <template
        slot="row-details"
        slot-scope="row"
      >
        ...
      </template>
    </v-table>
    

    VTable表

    我还尝试在全局组件中创建一个自定义的命名槽

    <template>
      <div>
        <b-table
          ...
        >
          <slot name="customRendering"/>
        </b-table>
      </div>
    </template>
    

    像这样使用它

    <v-table
      ...
    >
      <template slot="customRendering">
        <template
          slot="timestamp"
          slot-scope="data"
        >
          ...
        </template>
        <template
          slot="row-details"
          slot-scope="row"
        >
           ...
        </template>
      </template>
    </v-table>
    

    没有成功

    这可以简单地使用在grand child组件中定义的命名槽,还是完全不可能? 我还想循环一下 customRendering

    1 回复  |  直到 7 年前
        1
  •  1
  •   Daniel    7 年前

    在你的 vtable 组件,可以定义要传递的插槽。

    如果你有一个组件 my-component 带着孩子-> 延伸-> btable ...

    您可以定义 组件,您要使用

    <template
      slot="row-details"
      slot-scope="row"
    >
        <slot name="row-details"/>
    </template>
    

    下面是一个快速的例子 https://jsfiddle.net/eywraw8t/308324/

    您可能需要为每个插槽设置此选项。如果您想动态地传递它们(不知道它们的名称),那么呈现函数会更好地工作,因为您可以循环父级发送的所有插槽,并将它们传递给子级。

    文件: https://vuejs.org/v2/guide/render-function.html#Slots

    具有渲染功能的组件示例,该组件将向下传递作用域插槽

    const Bar = Vue.component('vtable', {
      render(h) {
        const children = Object.keys(this.$slots).map(slot => h('template', { slot }, this.$slots[slot]))
        return h('wrapper', [
          h('foo', {
            attrs: this.$attrs,
            on: this.$listeners,
            scopedSlots: this.$scopedSlots,
          }, children)
        ])
      }
    });