使用插槽将行模板传递给父组件的vue boostrap表

Man*_*uel 2 javascript vue.js bootstrap-vue

我有一个名为"List"的组件,其中包含一个vue boostrap表:

<template>
  <div>
    <b-table :items="items">
      <!--<template slot="createdAt" slot-scope="row"> usually vue boostrap table row templates live here-->
        <!--{{row.item.createdAt|dateFormatter}}-->
      <!--</template>-->
      <slot name="tableTemplates"></slot> <!-- but i want to pass the templates from my parent template -->
    </b-table>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

我从父组件"Orders"传递表项.我还想将行模板传递给vue boostrap b-table组件.

不幸的是我无法使用插槽工作(这将是模板内的模板)

<template>
  <div>
    <list :items="items">
      <template slot="tableTemplates">
        <!--templates inside templates do not work-->
        <template slot="id" slot-scope="row">
          <span v-b-tooltip.hover :title="row.item.id">{{row.item.id|uuidFormatter}}</span>
        </template>
        <template slot="createdAt" slot-scope="row">
          {{row.item.createdAt|dateFormatter}}
        </template>
        <template slot="customer" slot-scope="row">
          {{row.item.customer}}
        </template>
      </template>
    </list>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

cra*_*bly 8

您只需更改IVO的答案并使List组件通用即可.
这是一种可能的方法:

列表组件模板:

<template>
  <b-table striped hover :items="items">
    <template :slot="slot.field" slot-scope="row" v-for="slot in slots">
      <slot :name="slot.name" :tbl="row"></slot>
    </template>
  </b-table>
</template>
Run Code Online (Sandbox Code Playgroud)

列出组件道具:

  props: {
    items: {
      type: Array
    },
    slots: {
      type: Array
    }
  },
Run Code Online (Sandbox Code Playgroud)

然后,在任何父组件(使用List)中,您可以定义一个templatesdata属性,并将一组模板指令传递给List组件.在该示例中,我使用了一组对象来传递动态插槽名称和表数据字段.

父组件templates数据属性:

  data() {
    return {
      ...
      templates: [
        {
          name: "templateName",
          field: "dataFieldName"
        },
        ...
      ]
    };
  },
Run Code Online (Sandbox Code Playgroud)

父组件模板,列表用法:

  <list :items="items" :slots="templates">
    <template slot="customSlotName" slot-scope="data">
        // Custom template here...
    </template>
  </list>
Run Code Online (Sandbox Code Playgroud)

这将使所有自定义模板逻辑保留在父组件中,例如.Order.vue,而不是List.vue.

这是更新的代码框:https://codesandbox.io/s/244p9rx10n