当前位置:首页 > VUE

vue 实现表格固定列

2026-02-24 04:04:01VUE

Vue 实现表格固定列的方法

使用 CSS 固定列

通过 CSS 的 position: sticky 属性可以实现列的固定效果。适用于简单的表格布局,无需额外库支持。

<template>
  <div class="table-container">
    <table>
      <thead>
        <tr>
          <th class="fixed-column">固定列</th>
          <th>列1</th>
          <th>列2</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data" :key="item.id">
          <td class="fixed-column">{{ item.fixed }}</td>
          <td>{{ item.col1 }}</td>
          <td>{{ item.col2 }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.table-container {
  overflow-x: auto;
  max-width: 100%;
}
.fixed-column {
  position: sticky;
  left: 0;
  background-color: white;
  z-index: 1;
}
</style>

使用第三方库(如 Element UI)

Element UI 的 el-table 组件内置固定列功能,通过 fixed 属性即可实现。

<template>
  <el-table :data="data" style="width: 100%">
    <el-table-column prop="fixed" label="固定列" fixed width="150"></el-table-column>
    <el-table-column prop="col1" label="列1" width="200"></el-table-column>
    <el-table-column prop="col2" label="列2" width="200"></el-table-column>
  </el-table>
</template>

自定义滚动监听

对于复杂场景,可通过监听滚动事件动态控制列的样式。

<template>
  <div class="scroll-container" @scroll="handleScroll">
    <table>
      <thead>
        <tr>
          <th :class="{ 'fixed-column': isFixed }">固定列</th>
          <th>列1</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data" :key="item.id">
          <td :class="{ 'fixed-column': isFixed }">{{ item.fixed }}</td>
          <td>{{ item.col1 }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isFixed: false
    };
  },
  methods: {
    handleScroll(e) {
      this.isFixed = e.target.scrollLeft > 0;
    }
  }
};
</script>

性能优化建议

  • 固定列数量不宜过多,避免渲染性能问题。
  • 大数据量时建议使用虚拟滚动(如 vue-virtual-scroller)。
  • 第三方库的固定列功能通常已优化,优先考虑使用。

以上方法可根据项目需求选择,CSS 方案轻量但功能有限,第三方库功能全面但体积较大。

vue 实现表格固定列

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

相关文章

vue实现防抖节流

vue实现防抖节流

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

vue里实现增删改查

vue里实现增删改查

在Vue中实现增删改查 数据初始化 在Vue组件的data中定义初始数据和表单绑定的变量: data() { return { items: [ { id: 1, name…

vue实现建模

vue实现建模

Vue 实现建模的方法 在 Vue 中实现建模通常涉及数据绑定、组件化和状态管理。以下是几种常见的方法: 数据驱动建模 Vue 的核心是数据驱动视图。通过定义数据模型,Vue 会自动更新 DOM。…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

javascript实现vue

javascript实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,主要包括数据绑定、响应式系统和虚拟 DOM。以下是一个简化的实现示例。 数据响应式系统 通过 Object.d…

vue实现list

vue实现list

Vue 实现列表渲染 在 Vue 中,可以使用 v-for 指令来渲染列表。v-for 指令基于一个数组或对象来渲染一个列表,可以遍历数组或对象的属性。 基本列表渲染 <template&g…