Skip to content

Vue VtCheckbox 布尔勾选 ​

布尔列:单元格里直接画一个可点的勾选框。

示例 ​

微应用尚未挂载。

源码 ​

点击查看源码
vue
<template>
  <div class="demo-wrapper">
    <h3 class="demo-title">Vue VtCheckbox 布尔勾选</h3>
    <div class="status-text">{{ status }}</div>
    <div ref="containerRef" style="width: 820px; height: 600px" class="demo-container">
      <VirtTableVue :columns="columns" :options="options" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { VirtTableVue, type VueTableColumn } from '@virt-table/vue';
import { VtCheckbox } from '@virt-table/vanilla/components';

const ROW_COUNT = 5000;

const columns: VueTableColumn[] = [
  { key: 'id', title: 'ID', width: 80, align: 'center' },
  { key: 'name', title: '名称', width: 160 },
  VtCheckbox({ key: 'enabled', title: '启用', width: 100, align: 'center' }),
  // 值不是布尔:勾选写回 'Y'、取消写回 'N'
  VtCheckbox({ key: 'vip', title: 'VIP', width: 100, align: 'center', trueValue: 'Y', falseValue: 'N' }),
  // 数字 1/0
  VtCheckbox({ key: 'audited', title: '已审核', width: 110, align: 'center', trueValue: 1, falseValue: 0 }),
  // 只读回显
  VtCheckbox({ key: 'locked', title: '锁定(只读)', width: 130, align: 'center', disabled: true }),
];

const list = Array.from({ length: ROW_COUNT }, (_, i) => ({
  id: i,
  name: `条目 ${i}`,
  enabled: i % 2 === 0,
  vip: i % 3 === 0 ? 'Y' : 'N',
  audited: i % 4 === 0 ? 1 : 0,
  locked: i % 5 === 0,
}));

const options = {
  list,
  itemKey: 'id',
  estimatedSize: 40,
  buffer: 4,
  border: true,
};

const containerRef = ref<HTMLElement | null>(null);
const status = ref('');

const refresh = () => {
  const on = list.filter((r) => r.enabled).length;
  const vip = list.filter((r) => r.vip === 'Y').length;
  status.value = `VtCheckbox:点一下即写回(不弹编辑浮层,所以不需要 vtCellEditor 插件)。当前启用 ${on} 行、VIP ${vip} 行`;
};

// 勾选写回后统计要跟着变。组件内部改的是行数据,冒泡上来的 change 事件是最省事的信号
onMounted(() => {
  refresh();
  containerRef.value?.addEventListener('change', refresh);
});
onUnmounted(() => {
  containerRef.value?.removeEventListener('change', refresh);
});
</script>

说明 ​

「直接可点」类组件:交互与写回都发生在常态里,点一下就改值,不提供 renderEditor,也不需要 vtCellEditor 插件。给了 renderEditor 的话,装了编辑插件的人点勾选框会先弹出一个盖住勾选框的浮层,得点第二下才切换 —— 对一个开关型控件是纯粹的多余。

值不是 true / false 时配 trueValue / falseValue(1/0、'Y'/'N' 都常见)。

用字符串枚举时必须显式配 trueValue

不配就退回 JS 真值判断,'N'、'0' 这种非空字符串会被判成真。配了 trueValue 就只认它(严格相等)。

代价是这一列不参与「编辑态」语义(Esc 撤销、openCellEditor() 打开)—— 布尔列本来也没有可撤销的中间状态。皮肤直接用核心的 .vt-cell-bool + .vt-checkbox,与只读版 cellType: 'checkbox' 同源,视觉必然一致。

区别只在外观、值语义完全相同的还有 VtSwitch。

相关 API ​

字段作用
trueValue / falseValue写回的值,默认 true / false
col.align布尔列一般配 center

全量选项表见 单元格组件;公共选项 (placeholder / disabled / clearable / onChange)、asCell()、三类交互模型见 同页上方;列的通用字段见 列配置。

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