Skip to content

Vue 字段配置(列显隐 / 列序) ​

字段配置面板 = 勾选控制列显隐 + 拖手柄调整列序。列支持 hidden(默认隐藏)与 hideable: false(禁止在面板切换)。装载 vtFieldConfig() 后用 ref 上的 toggleFieldConfig(anchor) 打开面板,或用 setColumnVisible(key, visible) / moveColumn() 编程控制。

装了 vtToolbar 时它会把自己挂成工具栏上的「字段配置」那颗按钮 —— 工具栏一颗都不自带,所以这个插件(或 ...vtToolbarPanels() 那个预设)必须写出来。选项见 vanilla 版。

示例 ​

微应用尚未挂载。

源码 ​

点击查看源码
vue
<template>
  <div class="demo-wrapper">
    <h3 class="demo-title">Vue 字段配置</h3>
    <div class="virt-table-controls">
      <button
        type="button"
        class="virt-table-btn virt-table-btn-primary"
        @click="togglePanel"
      >
        字段配置
      </button>
      <button type="button" class="virt-table-btn" @click="tableRef?.setColumnVisible('job', false)">
        隐藏「职位」
      </button>
      <button type="button" class="virt-table-btn" @click="tableRef?.setColumnVisible('email', true)">
        显示「邮箱」
      </button>
      <span class="demo-note">ID 列不可隐藏;邮箱列默认隐藏</span>
    </div>
    <div style="width: 760px; height: 460px" class="demo-container">
      <VirtTableVue ref="tableRef" :columns="columns" :options="options" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { VirtTableVue, type VueTableColumn, vtFieldConfig } from '@virt-table/vue';
import { faker } from '@faker-js/faker';
import type { VirtTableVueInstance } from '../../virt-table-ref';

interface Row extends Record<string, unknown> {
  id: number;
  name: string;
  age: number;
  city: string;
  job: string;
  email: string;
}

const columns: VueTableColumn<Row>[] = [
  { key: 'id', title: 'ID', width: 80, hideable: false },
  { key: 'name', title: '姓名', width: 160 },
  { key: 'age', title: '年龄', width: 120 },
  { key: 'city', title: '城市', width: 160 },
  { key: 'job', title: '职位', width: 200 },
  { key: 'email', title: '邮箱', width: 240, hidden: true },
];

const list: Row[] = Array.from({ length: 500 }, (_, i) => ({
  id: i + 1,
  name: faker.person.fullName(),
  age: faker.number.int({ min: 18, max: 60 }),
  city: faker.location.city(),
  job: faker.person.jobTitle(),
  email: faker.internet.email(),
}));

const options = {
  list,
  itemKey: 'id',
  estimatedSize: 40,
  buffer: 6,
  border: true,
  plugins: [vtFieldConfig()],
};

const tableRef = ref<VirtTableVueInstance | null>(null);

// 面板要贴着触发按钮定位,所以把按钮本身作为 anchor 传进去
const togglePanel = (e: MouseEvent) => {
  tableRef.value?.toggleFieldConfig(e.currentTarget as HTMLElement);
};
</script>

说明 ​

相关 API ​

字段 / 方法作用详见
col.hidden / col.hideable默认隐藏 / 允不允许用户切换列配置 · 列显隐
setColumnVisible(colKey, visible)编程式显隐列配置 · 列显隐
getVisibleColumns / getLeafColumns / getAllColumns三种读列口径实例方法
toggleFieldConfig(anchor?)打开 / 关闭面板插件机制
moveColumn(fromKey, toKey, after)编程式换序(面板里拖手柄落的就是它)实例方法
getState() / setState()把列显隐存下来状态持久化

上面的字段在 Vue 端原样透传(实例方法通过组件 ref 调用)。封装层特有的部分 —— 组件 Props、渲染函数返回 VNode、ref 转发了哪些方法 —— 见 Vue API。