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

Nuxt3中用Tanstack Table/AG Grid替换v-for渲染数据的方法

下面分别给出用Tanstack Table和AG Grid替换原有v-for渲染逻辑的具体实现方案,基于Nuxt3的<script setup>语法:


使用Tanstack Table重构的方案

1. 安装依赖

在项目根目录执行命令:

npm install @tanstack/vue-table

2. 组件完整代码

<script setup>
import { useVueTable, createColumnHelper } from '@tanstack/vue-table'

// 保留你原有的数据获取逻辑
const users = await $fetch('你的用户数据接口地址')

// 创建列配置助手
const columnHelper = createColumnHelper()

// 定义表格列(这里只保留用户名称列,可按需添加其他字段)
const columns = [
  columnHelper.accessor('name', {
    header: '用户名称',
    cell: (info) => info.getValue(),
  }),
]

// 初始化表格实例
const table = useVueTable({
  data: users,
  columns,
})
</script>

<template>
  <div class="custom-table">
    <table>
      <thead>
        <tr v-for="headerGroup in table.getHeaderGroups()" :key="headerGroup.id">
          <th v-for="header in headerGroup.headers" :key="header.id" :colspan="header.colSpan">
            {{ header.isPlaceholder ? '' : header.renderHeader() }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="row in table.getRowModel().rows" :key="row.id">
          <td v-for="cell in row.getVisibleCells()" :key="cell.id">
            {{ cell.renderCell() }}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.custom-table table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #e5e7eb;
  padding: 0.75rem;
  text-align: left;
}
th {
  background-color: #f3f4f6;
  font-weight: 500;
}
</style>

使用AG Grid重构的方案

1. 安装依赖

在项目根目录执行命令:

npm install ag-grid-vue3 ag-grid-community

2. 组件完整代码

<script setup>
import { AgGridVue } from 'ag-grid-vue3'
// 导入AG Grid基础样式和主题样式
import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-alpine.css'

// 保留你原有的数据获取逻辑
const users = await $fetch('你的用户数据接口地址')

// 定义表格列配置
const columnDefs = [
  { field: 'name', headerName: '用户名称' },
  // 可按需添加其他列,比如 { field: 'id', headerName: '用户ID' }
]

// 可选:设置全局列默认属性(如排序、过滤、调整宽度)
const defaultColDef = {
  sortable: true,
  filter: true,
  resizable: true,
}
</script>

<template>
  <!-- AG Grid需要指定主题容器,同时设置宽高 -->
  <div class="ag-theme-alpine" style="height: 400px; width: 100%">
    <AgGridVue
      :rowData="users"
      :columnDefs="columnDefs"
      :defaultColDef="defaultColDef"
    />
  </div>
</template>

两种方案均保留了你原有的$fetch数据获取逻辑,仅替换了渲染部分:

  • Tanstack Table属于轻量型表格库,自定义自由度高,适合需要高度定制UI的场景
  • AG Grid功能更全面,自带排序、过滤、分页等开箱即用的功能,适合复杂数据表格场景

内容的提问来源于stack exchange,提问作者Naga Vijayapuram

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:22:46