当前位置:首页 > VUE

vue实现table表格滚动

2026-02-23 16:20:48VUE

Vue 实现表格滚动的方法

使用 CSS 固定表头并滚动内容

通过 CSS 设置表格容器的高度和溢出属性,实现表头固定、内容滚动的效果。

<template>
  <div class="table-container">
    <table>
      <thead>
        <tr>
          <th v-for="col in columns" :key="col.key">{{ col.title }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="row in data" :key="row.id">
          <td v-for="col in columns" :key="col.key">{{ row[col.key] }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.table-container {
  height: 300px;
  overflow-y: auto;
}
thead {
  position: sticky;
  top: 0;
  background: white;
}
</style>

使用第三方组件库

Element UI 或 Ant Design Vue 等库提供了现成的滚动表格组件。

vue实现table表格滚动

<template>
  <el-table :data="tableData" height="250">
    <el-table-column prop="date" label="日期"></el-table-column>
    <el-table-column prop="name" label="姓名"></el-table-column>
  </el-table>
</template>

虚拟滚动优化性能

对于大数据量表格,使用虚拟滚动技术只渲染可见区域的行。

vue实现table表格滚动

<template>
  <virtual-list :size="50" :remain="10" :data="bigData">
    <table>
      <tr v-for="item in virtualData" :key="item.id">
        <td>{{ item.name }}</td>
      </tr>
    </table>
  </virtual-list>
</template>

横向滚动实现

当列数过多时,可以添加水平滚动条。

.table-container {
  overflow-x: auto;
  white-space: nowrap;
}

动态计算高度

根据窗口大小动态调整表格高度。

mounted() {
  this.calcHeight();
  window.addEventListener('resize', this.calcHeight);
},
methods: {
  calcHeight() {
    this.tableHeight = window.innerHeight - 200;
  }
}

以上方法可以根据实际需求选择使用,CSS 方案最简单,虚拟滚动适合大数据量,组件库方案最便捷。

标签: 表格vue
分享给朋友:

相关文章

vue实现好友列表

vue实现好友列表

实现好友列表的Vue组件 数据准备 在Vue组件的data中定义好友列表数据,通常是一个数组对象,每个对象包含好友的基本信息如ID、头像、昵称等。 data() { return {…

vue实现div

vue实现div

Vue 实现 DIV 元素的方法 在 Vue 中实现 DIV 元素可以通过多种方式,以下是几种常见的实现方法: 使用模板语法 在 Vue 的模板中直接使用 HTML 的 <div> 标…

vue 实现tabs

vue 实现tabs

Vue 实现 Tabs 组件的方法 使用动态组件和 v-for 在 Vue 中实现 Tabs 可以通过动态组件和 v-for 指令结合完成。定义一个 tabs 数组,包含每个标签的标题和对应的组件。…

vue 实现过滤

vue 实现过滤

Vue 实现过滤的方法 在 Vue 中实现过滤功能可以通过多种方式完成,包括使用计算属性、自定义过滤器、第三方库等。以下是几种常见的实现方法: 使用计算属性进行过滤 计算属性是 Vue 中最常用的…

vue alert实现

vue alert实现

使用 Vue 实现 Alert 组件 在 Vue 中实现 Alert 组件可以通过自定义组件或结合第三方库完成。以下是几种常见方法: 自定义 Alert 组件 创建一个可复用的 Alert 组件,…

实现vue table

实现vue table

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。 <template> <tabl…