You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Vuetify Data-Table添加左侧序号列?

给Vuetify Data-Table添加序号列的解决方案

步骤1:修改表头配置

在headers数组最前端添加序号列的定义,设置显示文本、对齐方式,并禁用排序和筛选:

headers: [
  { text: "序号", align: "center", sortable: false, filterable: false },
  // 原有的表头项
  {
    text: "Year",
    align: "start",
    filterable: true,
    value: "fields.year",
  },
  { text: "Item", value: "fields.item" },
  { text: "Element", value: "fields.element" },
  { text: "Value", value: "fields.value" },
  { text: "Unit", value: "fields.unit" },
  { text: "Area Code", value: "fields.area_code" },
  { text: "Area", value: "fields.area" },
],

步骤2:添加序号列的自定义渲染模板

在v-data-table组件内部,使用body.prepend插槽渲染每一行的序号,分两种场景处理:

无分页版本(直接使用索引计算)

完整模板代码如下:

<template>
  <v-card>
    <v-card-title>
      <v-text-field
        v-model="search"
        append-icon="mdi-magnify"
        label="Search"
        single-line
        hide-details
      ></v-text-field>
    </v-card-title>
    <v-data-table
      :headers="headers"
      :items="products.records"
      :search="search"
      :loading="isLoading"
    >
      <!-- 渲染序号列 -->
      <template #body.prepend="{ index }">
        <td class="text-center">{{ index + 1 }}</td>
      </template>
    </v-data-table>
  </v-card>
</template>

支持分页版本(结合分页参数计算)

如果需要启用分页,先在data中添加分页变量:

data() {
  return {
    search: "",
    headers: [/* 修改后的表头 */],
    isLoading: true,
    page: 1, // 当前页码
    itemsPerPage: 10, // 每页条数
  };
},

再修改表格和插槽内容,同时可添加分页控件:

<v-data-table
  :headers="headers"
  :items="products.records"
  :search="search"
  :loading="isLoading"
  :page.sync="page"
  :items-per-page="itemsPerPage"
>
  <template #body.prepend="{ index }">
    <td class="text-center">
      {{ (page - 1) * itemsPerPage + index + 1 }}
    </td>
  </template>
  <!-- 可选:添加分页控件 -->
  <template #bottom>
    <v-pagination
      v-model="page"
      :length="Math.ceil(products.records.length / itemsPerPage)"
      class="justify-center"
    ></v-pagination>
  </template>
</v-data-table>

效果说明

修改后表格左侧会出现固定序号列,序号随数据行同步更新,搜索、筛选操作不会破坏序号的连续性。

内容的提问来源于stack exchange,提问作者Amit Amar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:35:32