当前位置:首页 > VUE

vue实现表头固定

2026-02-20 13:12:13VUE

Vue 实现表头固定的方法

使用 CSS 固定表头

通过 CSS 的 position: sticky 属性可以轻松实现表头固定。这种方法不需要额外的 JavaScript 代码,兼容性较好。

<template>
  <div class="table-container">
    <table>
      <thead>
        <tr>
          <th>Header 1</th>
          <th>Header 2</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in items" :key="index">
          <td>{{ item.field1 }}</td>
          <td>{{ item.field2 }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.table-container {
  height: 300px;
  overflow-y: auto;
}

thead th {
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 10;
}
</style>

使用第三方库

如果需要更复杂的功能(如排序、分页),可以使用第三方表格库如 Element UIVxeTable

Element UI 为例:

<template>
  <el-table
    :data="tableData"
    height="250"
    style="width: 100%">
    <el-table-column
      prop="date"
      label="Date"
      width="180">
    </el-table-column>
    <el-table-column
      prop="name"
      label="Name"
      width="180">
    </el-table-column>
  </el-table>
</template>

动态计算表格高度

对于需要动态计算表格高度的情况,可以通过监听窗口大小变化来调整表格高度。

export default {
  data() {
    return {
      tableHeight: 0
    }
  },
  mounted() {
    this.calculateHeight()
    window.addEventListener('resize', this.calculateHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateHeight)
  },
  methods: {
    calculateHeight() {
      this.tableHeight = window.innerHeight - 200 // 减去其他元素的高度
    }
  }
}

注意事项

  • 使用 CSS 方法时,确保表格容器有固定高度和 overflow-y: auto
  • 如果表格内容过多,考虑分页或虚拟滚动以提高性能。
  • 在移动端使用时,测试 position: sticky 的兼容性。

vue实现表头固定

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

相关文章

vue实现防抖节流

vue实现防抖节流

Vue 中实现防抖(Debounce) 防抖的核心是延迟执行函数,在连续触发时取消前一次的调用,只执行最后一次。适用于输入框搜索、窗口大小调整等场景。 方法1:使用 Lodash 的 _.debo…

vue实现飘窗原理

vue实现飘窗原理

vue实现飘窗原理 飘窗效果通常指在页面上悬浮显示的弹窗或通知,跟随页面滚动或固定在某个位置。Vue实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组…

vue实现方法

vue实现方法

Vue 实现方法 Vue 是一种流行的前端框架,用于构建用户界面和单页应用。以下是几种常见的 Vue 实现方法: 创建 Vue 实例 通过 new Vue() 创建一个 Vue 实例,传入配置对象,…

vue功能实现

vue功能实现

Vue 功能实现指南 Vue.js 是一个渐进式 JavaScript 框架,广泛用于构建用户界面。以下是 Vue 功能的常见实现方法。 数据绑定 Vue 的核心功能之一是数据绑定,通过 v-mod…

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue实现mouseout

vue实现mouseout

Vue 实现 mouseout 事件的方法 在 Vue 中实现 mouseout 事件可以通过多种方式完成,以下是几种常见的方法: 使用 v-on 指令 Vue 提供了 v-on 指令(或简写为…