Skip to content

Vue VtSwitch 开关 ​

开关列。值语义与交互模型和 VtCheckbox 完全一致(共用同一套真值判定与写回),差别只在外观:一个轨道 + 一个滑块,可以另配开 / 关文案。

示例 ​

微应用尚未挂载。

源码 ​

点击查看源码
vue
<template>
  <div class="demo-wrapper">
    <h3 class="demo-title">Vue VtSwitch 开关</h3>
    <div class="status-text">{{ status }}</div>
    <div style="width: 840px; height: 600px" class="demo-container">
      <VirtTableVue :columns="columns" :options="options" />
    </div>
  </div>
</template>

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

const ROW_COUNT = 5000;

const lastChange = ref('(未操作)');
// 计数要在写回后重算,用一个递增的 tick 触发 computed 重新求值
const tick = ref(0);

const columns: VueTableColumn[] = [
  { key: 'id', title: 'ID', width: 80, align: 'center' },
  { key: 'name', title: '名称', width: 160 },
  VtSwitch({
    key: 'enabled',
    title: '启用',
    width: 110,
    onChange: (v, row) => {
      lastChange.value = `${(row as { name: string }).name} → ${v}`;
      tick.value++;
    },
  }),
  // 带文案
  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: ROW_COUNT }, (_, i) => ({
  id: i,
  name: `条目 ${i}`,
  enabled: i % 2 === 0,
  notify: i % 3 === 0,
  mode: i % 4 === 0 ? 'on' : 'off',
  locked: i % 5 === 0,
}));

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

const status = computed(() => {
  tick.value; // 依赖它,写回后重算
  const on = list.filter((r) => r.enabled).length;
  return `VtSwitch:点一下即写回,与 VtCheckbox 同一套值语义(trueValue / falseValue)。启用 ${on} 行 · 最近一次 onChange:${lastChange.value}`;
});
</script>

说明 ​

「直接可点」类组件:点一下就写回,不提供 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()、三类交互模型见 同页上方;列的通用字段见 列配置。

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