MST

星途 面试题库

面试题:Vue中如何在复杂表格组件插槽设计里实现具名插槽的合理运用

在一个复杂表格组件中,假设表头需要插槽自定义,表体每行数据展示也需要插槽自定义。请描述如何使用具名插槽分别实现表头和表体的自定义插槽设计,并给出关键代码示例。
40.7万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

1. 使用具名插槽实现表头和表体自定义插槽设计的描述

  • 表头自定义插槽:在表格组件中,定义一个具名插槽用于表头部分。父组件使用该表格组件时,通过具名插槽将自定义的表头内容传入表格组件,表格组件在合适位置渲染该插槽内容。
  • 表体自定义插槽:同样在表格组件中,定义另一个具名插槽用于表体每行数据展示。父组件在使用表格组件时,为每行数据通过此具名插槽传入自定义的展示内容,表格组件在渲染表体行时,渲染对应的具名插槽内容。

2. 关键代码示例

假设使用 Vue 框架:

表格组件代码(子组件 TableComponent.vue

<template>
  <table>
    <thead>
      <tr>
        <slot name="header"></slot>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(item, index) in dataList" :key="index">
        <slot name="body" :item="item"></slot>
      </tr>
    </tbody>
  </table>
</template>

<script>
export default {
  data() {
    return {
      dataList: [
        { name: 'John', age: 25 },
        { name: 'Jane', age: 30 }
      ]
    }
  }
}
</script>

父组件使用表格组件代码(ParentComponent.vue

<template>
  <div>
    <TableComponent>
      <template v-slot:header>
        <th>Name</th>
        <th>Age</th>
      </template>
      <template v-slot:body="slotProps">
        <td>{{ slotProps.item.name }}</td>
        <td>{{ slotProps.item.age }}</td>
      </template>
    </TableComponent>
  </div>
</template>

<script>
import TableComponent from './TableComponent.vue'

export default {
  components: {
    TableComponent
  }
}
</script>

上述代码中,在 TableComponent.vue 中定义了 headerbody 两个具名插槽分别用于表头和表体自定义。在 ParentComponent.vue 中,通过 v-slot 语法为这两个具名插槽传入自定义内容。表头插槽中自定义了表头列名,表体插槽中根据传入的 item 数据自定义每行展示内容。