vue修改父组件中的v-data-table列项模板

KDa*_*ani 2 vue.js vue-component

我正在使用Vuetify并制作了一个包含v-data-table. 如何更改父组件中的表格列模板?

子组件示例:

<template>
  <v-card>
    <v-data-table :items="items" :headers="headers">
      <!-- ???????? -->
    </v-data-table>
  </v-card>
</template>

<script>
export default {
  name: "ChildComponent",
  props: {
    items: Array,
    headers: Array,
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

父组件:

item.id只是一个例子,我需要一个适用于任何类型的对象字段的通用解决方案。

<template>
  <ChildComponent :items="items" :headers="headers">
    <template v-slot:item.id="{ item }">
      <v-chip> {{ item.id }} </v-chip>
    </template>
  </ChildComponent>
</template>

<script>
import ChildComponent from "./ChildComponent";

export default {
  components: {
    ChildComponent,
  },
  data: () => ({
    items: [/* ... */],
    headers: [/* ... */],
  }),
};
</script>
Run Code Online (Sandbox Code Playgroud)

我想我需要动态插槽,但并不真正知道如何在这种情况下使用它们。

KDa*_*ani 5

需要ChildComponent按以下方式修改:

<template>
  <v-card>
    <v-data-table :items="items" :headers="headers">
      <template
        v-for="header in headers"
        v-slot:[`item.${header.value}`]="{ item }"
      >
        <slot :name="[`item.${header.value}`]" :item="item">
          {{ getVal(item, header.value) }}
        </slot>
      </template>
    </v-data-table>
  </v-card>
</template>

<script>
export default {
  name: "childComponent",
  props: {
    items: Array,
    headers: Array,
  },
  methods: {
    /*
    https://stackoverflow.com/a/40270942/6936938
    */
    getVal(item, path) {
      return path.split(".").reduce((res, prop) => res[prop], item);
    },
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

getVal方法适用于嵌套项目字段。没有它你就不能使用像item.author.name.