Vue-将插槽向下传递到子组件

问题描述 投票:0回答:1

我想从Vuetify制作可重用的数据表组件。有些列可能包含v-slot来修改该列中的数据。例如:我将用户角色存储为整数,并希望它们显示为user或adminin the table. Currently I do this with thisv-slot`:

 <template v-slot:item.role="{item} ">
    {{ (item.role === 1) ? 'Administrator' : 'User' }}
 </template>

因为这不是每个数据表的用例,所以我想从使用数据表的父组件传递这些v-slot。我的数据表组件当前看起来像这样:

<template>
  <v-data-table :headers="headers" :items="items">
    <template v-slot:item.role="{item} ">
      {{ (item.role === 1) ? 'Administrator' : 'User' }}
    </template>
    <template v-slot:item.action="{ item }">
      <v-icon @click="deleteItem(item)" small>fas fa-trash</v-icon>
    </template>
  </v-data-table>
</template>

<script>
export default {
  name: "DataTable",
  props: {
    title: String,
    headers: Array,
    items: Array
  },
  methods: {
    deleteItem(item) {
      this.$emit("clicked", item);
    }
  }
};
</script>

这是我使用DataTable的组件(UserTable.vue):

<template>
  <DataTable :title="title" :headers="headers" :items="items" @clicked="onDelete" />
</template>

<script>
import DataTable from "../../../components/DataTable";
import axios from "axios";

export default {
  name: "UserTable",
  components: {
    DataTable
  },
  props: {
    items: Array
  },
  data: () => ({
    title: "Users",
    headers: [
      {
        text: "Name",
        value: "name"
      },
      {
        text: "Email",
        value: "email"
      },
      {
        text: "Role",
        value: "role"
      },
      { text: "Actions", value: "action", sortable: false }
    ],
  }),
  methods: {
    onDelete(item) {
      this.$emit("clicked", item);
    }
  }
};
</script> 

在理想情况下,我希望在UserTable组件中具有以下内容:

<template>
  <DataTable :title="title" :headers="headers" :items="items" @clicked="onDelete">
      <template v-slot:item.role="{item} ">
      {{ (item.role === 1) ? 'Administrator' : 'User' }}
    </template>
    <template v-slot:item.action="{ item }">
      <v-icon @click="deleteItem(item)" small>fas fa-trash</v-icon>
    </template>
  </DataTable>
</template>

然后像这样保持DataTable的干净简洁:

<template>
  <v-data-table :headers="headers" :items="items">
    <slot></slot>
  </v-data-table>
</template>

但是显然,这似乎不符合我的预期,因为它现在在所需的列中未显示任何内容。我创建了一个CodeSandBox,让您看看现在的状态:

https://codesandbox.io/s/priceless-bohr-oxu18?fontsize=14&hidenavigation=1&theme=dark

有人可以告诉我为什么我的方法行不通或怎么解决吗?

vue.js
1个回答
0
投票

通过查看以下答案,我设法解决了这个问题:https://stackoverflow.com/a/52823029/7603806

<template v-for="slot in Object.keys($scopedSlots)" :slot="slot" slot-scope="scope"><slot :name="slot" v-bind="scope"/></template>

我在DataTable组件中添加了上面的代码,现在从使用UserTableDataTable组件传递了插槽。

© www.soinside.com 2019 - 2024. All rights reserved.