VtSwitch 开关
开关列。值语义与交互模型和 VtCheckbox 完全一致(共用同一套真值判定与写回),差别只在外观:一个轨道 + 一个滑块,可以另配开 / 关文案。
示例
微应用尚未挂载。
源码
点击查看源码
ts
import { VirtTable, type VirtTableColumn } from '@virt-table/vanilla';
import { VtSwitch } from '@virt-table/vanilla/components';
export function bootstrapTableVtSwitch(root: HTMLElement): () => void {
const rowCount = 5000;
let lastChange = '(未操作)';
const columns: VirtTableColumn[] = [
{ key: 'id', title: 'ID', width: 80, align: 'center' },
{ key: 'name', title: '名称', width: 160 },
VtSwitch({
key: 'enabled',
title: '启用',
width: 110,
onChange: (v, row) => {
lastChange = `${(row as any).name} → ${v}`;
refresh();
},
}),
// 带文案
VtSwitch({ key: 'notify', title: '通知', width: 160, activeText: '已开启', inactiveText: '已关闭' }),
// 字符串枚举
VtSwitch({ key: 'mode', title: '模式', width: 150, trueValue: 'on', falseValue: 'off', activeText: 'on', inactiveText: 'off' }),
VtSwitch({ key: 'locked', title: '锁定(只读)', width: 130, disabled: true }),
];
const list = Array.from({ length: rowCount }, (_, i) => ({
id: i,
name: `条目 ${i}`,
enabled: i % 2 === 0,
notify: i % 3 === 0,
mode: i % 4 === 0 ? 'on' : 'off',
locked: i % 5 === 0,
}));
root.innerHTML = `
<div id="status" class="status-text"></div>
<div style="width:840px;height:600px;" class="demo-container" id="vtContainer"></div>
`;
const container = root.querySelector('#vtContainer') as HTMLElement;
const status = root.querySelector('#status') as HTMLElement;
const table = new VirtTable(container, {
list,
columns,
itemKey: 'id',
estimatedSize: 40,
buffer: 4,
border: true,
});
function refresh() {
const on = list.filter((r) => r.enabled).length;
status.textContent = `VtSwitch:点一下即写回,与 VtCheckbox 同一套值语义(trueValue / falseValue)。启用 ${on} 行 · 最近一次 onChange:${lastChange}`;
}
refresh();
return () => {
table.destroy();
root.innerHTML = '';
};
}说明
「直接可点」类组件:点一下就写回,不提供 renderEditor,也不需要 vtCellEditor 插件。
用字符串枚举时必须显式配 trueValue
不配就退回 JS 真值判断,'off' 这种非空字符串会被判成真。
用 <button role="switch"> 而不是 <input type="checkbox">:轨道 + 滑块要两层元素才画得出来,而 input 不能有子节点(伪元素能凑出来,但拿不到 aria-checked 那种明确的状态表达,读屏也读不出「开关」这个角色)。
相关 API
| 字段 | 作用 |
|---|---|
trueValue / falseValue | 写回的值,默认 true / false |
activeText / inactiveText | 开 / 关文案,不配就不画 |
全量选项表见 单元格组件;公共选项 (
placeholder/disabled/clearable/onChange)、asCell()、三类交互模型见 同页上方;列的通用字段见 列配置。