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

如何在Vue+Quasar的q-table中固定顶部栏并仅让内容滚动

固定Quasar q-table顶部栏并实现内容滚动

作为前端新手学习Vue + Quasar Framework,要实现q-table顶部包含“Fruits”标题和搜索按钮的栏位固定,仅让表格内容区域滚动,可以按照以下方式修改代码:

修改后的完整代码

<template>
  <q-table
    virtual-scroll
    class="fit"
    :style="{ height: 'calc(100vh - 64px)' }" <!-- 根据实际布局调整表格高度 -->
    :rows="fruits" <!-- 绑定你的数据源 -->
    :columns="columns" <!-- 定义列配置 -->
  >
    <template v-slot:top>
      <div class="q-pa-md flex items-center justify-between">
        <div class="text-h6">Fruits</div>
        <q-btn icon="search" />
      </div>
    </template>

    <template v-slot:body="props">
      <q-tr :props="props">
        <q-td :props="props">
          <div class="q-pa-xs col-xs-12 col-sm-6 col-md-4">
            <!-- 你的项目卡片内容 -->
            {{ props.row.name }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </q-table>
</template>

<script setup>
// 示例数据源和列配置,替换成你自己的数据
const columns = [
  { name: 'fruit', label: 'Fruit', field: 'name' }
];
const fruits = [
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Orange' },
  // 更多数据...
];
</script>

<style scoped>
.fit :deep(.q-table__top) {
  position: sticky;
  top: 0;
  background-color: #ffffff; /* 设置背景色防止内容穿透 */
  z-index: 10;
}

.fit :deep(.q-table__middle) {
  overflow-y: auto;
}

/* 如果需要固定表头,添加以下样式(top值需匹配顶部栏高度) */
.fit :deep(thead tr th) {
  position: sticky;
  top: 88px;
  background-color: #ffffff;
  z-index: 9;
}
</style>

关键说明

  1. 设置表格高度:给q-table指定明确高度(示例中用calc(100vh - 64px)适配全屏布局),这是内容区域能滚动的前提。
  2. 固定顶部栏:通过:deep(.q-table__top)选择器给top插槽容器设置sticky定位,配合背景色和z-index,确保滚动时顶部栏不会被内容覆盖。
  3. 内容区域滚动:.q-table__middle是表格内容的容器,设置overflow-y: auto让内容超出时自动显示垂直滚动条。
  4. 可选:固定表头:如果需要同时固定表头,给表头th设置sticky定位,top值要等于顶部栏的实际高度,保证表头紧跟在顶部栏下方固定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:27:48