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

Vue2+Vuetify中为vue-ads-table的_children行添加复选框

为vue-ads-table的子行添加复选框解决方案

由于vue-ads-table自带的selectable属性仅对顶级行生效,子行不会自动生成复选框,我们可以通过自定义列+插槽的方式实现需求,具体步骤如下:

1. 修改列配置(fields)

在你的列数组中新增一个自定义复选框列,指定关联的模板名称:

fields: [
  {
    name: 'checkbox',
    label: '',
    sortable: false,
    template: 'checkbox-template' // 关联后续的插槽模板
  },
  // 保留你原有的其他列
  { name: 'Name', label: '名称' },
  { name: 'Code', label: '编码' },
  { name: 'Email', label: '邮箱' },
  { name: 'Phone', label: '电话' }
]

2. 自定义复选框插槽

在vue-ads-table组件内添加插槽,为所有行(包括子行)渲染Vuetify复选框:

<vue-ads-table
  :columns="fields"
  :rows="items"
  class="my-table"
>
  <template slot="toggle-children-icon" slot-scope="props">
    <i class="mdi" :class="[props.expanded ? 'mdi-minus' : 'mdi-plus']"></i>
  </template>

  <!-- 自定义复选框模板插槽 -->
  <template slot="checkbox-template" slot-scope="props">
    <v-checkbox
      :value="isRowSelected(props.row)"
      @input="toggleRowSelection(props.row)"
      hide-details
      class="ma-0"
    ></v-checkbox>
  </template>
</vue-ads-table>

3. 实现选中状态管理

在组件的data和methods中处理行的选中状态,可按需添加父子行联动逻辑:

data() {
  return {
    selectedRows: new Set(), // 用Set存储选中行的ID,避免重复
    fields: [/* 上述列配置 */],
    items: [/* 你的数据源 */]
  }
},
methods: {
  // 判断当前行是否被选中
  isRowSelected(row) {
    return this.selectedRows.has(row._id);
  },
  // 切换行选中状态
  toggleRowSelection(row) {
    if (this.selectedRows.has(row._id)) {
      this.selectedRows.delete(row._id);
    } else {
      this.selectedRows.add(row._id);
    }

    // 可选:选中父行时自动选中所有子行
    if (row._children?.length) {
      row._children.forEach(child => {
        if (!this.selectedRows.has(child._id)) {
          this.selectedRows.add(child._id);
        }
      });
    }

    // 可选:子行全部选中时自动选中父行(需实现父行查找逻辑)
    // const parent = this.items.find(item => item._id === row.parentId);
    // if (parent) {
    //   const allChildrenSelected = parent._children.every(child => this.selectedRows.has(child._id));
    //   allChildrenSelected ? this.selectedRows.add(parent._id) : this.selectedRows.delete(parent._id);
    // }
  }
}

说明

  • 该方案通过自定义模板插槽,绕过组件默认的行选择逻辑,确保子行也能渲染复选框
  • 选中状态使用Set存储,保证ID唯一性,便于后续批量操作
  • 父子行联动逻辑为可选功能,可根据业务需求调整

内容的提问来源于stack exchange,提问作者Shafeeq Nt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 15:47:03