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

Bootstrap-Vue表格能否固定右侧列?如何实现左右列同时固定?

Bootstrap-Vue表格实现右侧列固定及左右列同时固定的方案

需求:在Bootstrap-Vue表格中固定右侧/最后一列,同时需要实现左右两侧列都固定的效果,但官方文档的Sticky功能仅支持左侧固定。

因为Bootstrap-Vue原生的stickyColumn仅支持左侧固定,我们可以通过自定义CSS结合字段配置来实现右侧固定的效果,具体实现如下:

1. 核心思路

  • 给需要固定在右侧的列添加自定义类名,比如sticky-right-column
  • 通过CSS设置该类的position: sticky和right: 0,同时设置背景色避免滚动时被其他内容覆盖
  • 左侧固定仍使用原生的stickyColumn: true配置

2. 完整实现代码

<template>
  <div>
    <div class="mb-2">
      <b-form-checkbox v-model="stickyHeader" inline>固定表头</b-form-checkbox>
      <b-form-checkbox v-model="noCollapse" inline>取消边框合并</b-form-checkbox>
    </div>
    <b-table
      :sticky-header="stickyHeader"
      :no-border-collapse="noCollapse"
      responsive
      :items="items"
      :fields="fields"
    >
      <!-- 使用text-nowrap类强制不换行,方便演示横向滚动 -->
      <template #head(id)="scope">
        <div class="text-nowrap">行ID</div>
      </template>
      <template #head(l)="scope">
        <div class="text-nowrap">最后一列</div>
      </template>
      <template #head()="scope">
        <div class="text-nowrap">
          表头 {{ scope.label }}
        </div>
      </template>
    </b-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      stickyHeader: true,
      noCollapse: false,
      fields: [
        // 左侧固定列(原生支持)
        { key: 'id', stickyColumn: true, isRowHeader: true, variant: 'primary' },
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
        'i',
        'j',
        'k',
        // 右侧固定列,添加自定义类名
        { key: 'l', class: 'sticky-right-column', variant: 'info' }
      ],
      items: Array.from({ length: 10 }, (_, idx) => ({
        id: idx + 1,
        a: 0, b: 1, c: 2, d: 3, e: 4, f: 5, g: 6, h: 7, i: 8, j: 9, k: 10, l: 11
      }))
    }
  }
}
</script>

<style scoped>
/* 右侧固定列的核心样式 */
.sticky-right-column {
  position: sticky !important;
  right: 0;
  /* 设置背景色避免滚动时被其他列内容穿透 */
  background-color: #fff;
  /* 提高层级避免被普通列遮挡 */
  z-index: 1;
}

/* 适配no-border-collapse模式下的边框样式 */
.table-no-border-collapse .sticky-right-column {
  border-left: 1px solid #dee2e6;
}
</style>

3. 效果与注意事项

  • 横向滚动时,左侧id列和右侧l列会固定在视图两侧,中间列正常滚动
  • 必须给固定列设置背景色,否则滚动时会出现内容穿透问题
  • 自定义CSS中的!important用于覆盖Bootstrap-Vue的默认样式,确保生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:05:24