Ant design vue 表格设置选中行进行设置复选框选中

时间:2024-03-13 12:18:58

常规情况下, 我们要想选中一条数据, 需要点击该行行首的复选框, 无奈复选框稍小, 因此想要实现如题功能, 用的是这款ui框架, 主要看它的样式都比较好看, 和elementui很相像, 不知道谁模仿谁, 感觉这个做的好一点而且提供了一套中后台权限管理系统模板.
但是有些功能 比如这个点击行进行选中, 没有很方便的在官网文档介绍中找到设置方法, 但是找到后感觉还是挺简单的( 毕竟是做后台的… 刚入工程化前端), 虽然elementui是很到位, 但是还是想要用这款ui, 实在是漂亮精致!Ant design vue 表格设置选中行进行设置复选框选中

这是效果
Ant design vue 表格设置选中行进行设置复选框选中

实现方法:
table标签添加 customRow 属性( 通过官网介绍得知 )

官网介绍
customRow 用法 #
适用于 customRow customHeaderRow customCell customHeaderCell。
遵循Vue jsx语法。

<Table
  customRow={(record) => {
    return {
      props: {
        xxx... //属性
      },
      on: { // 事件
        click: () => {},       // 点击行
        mouseenter: () => {},  // 鼠标移入行
        xxxx...
      },

    };
  )}
  customHeaderRow={(column) => {
    return {
      on: {
        click: () => {},        // 点击表头行
      }
    };
  )}
/>

这是完整的官网( 官网介绍 )的一个带多选框的表格演示代码进行改动后的代码

data() {
    return {
      data,
      columns,
      rowSelection :{
        selectedRowKeys: []   // 添加这个属性, 也就是他管理着选中行
      },
    }

然后table标签添加 :customRow属性并指向以下方法

setRow (record) {
      return {
        on: {
          click: () => {
            console.log(record.key)
            let flag = false
            let keys = []
            keys = this.rowSelection.selectedRowKeys
            if(keys.indexOf(record.key) >= 0) {
                flag=true
            }
            if(flag){
               keys.splice(keys.findIndex(item => item === record.key), 1)
            } else {
                keys.push(record.key)
            }       
            console.log(JSON.stringify(this.rowSelection.selectedRowKeys))
          }
        }
      }
    }

这是官网提供的后台项目的写法 和上面没关系
git的官方纯净项目 git地址
首先也是在table标签定义 customRow 然后在customRow的点击事件中进行业务逻辑操作, 增删选中行的数组this.selectedRowKeys

	let flag = false
    let keys = []
    keys = this.selectedRowKeys
    if(keys.indexOf(record.id) >= 0) {
        flag=true
    }
    if(flag){
        keys.splice(keys.findIndex(item => item === record.id), 1)
        this.selectedRows.splice(this.selectedRows.findIndex(item => item === record.id), 1)
    } else {
         keys.push(record.id)
         this.selectedRows.push(record)
     }


但是重要一点就是 只更新数组, 都不会设置选中复选框, 需要手动点击一次复选框之后就可以点行选框, 所以要继续设置

this.options = {
 rowSelection: {
    selectedRowKeys: this.selectedRowKeys,
    onChange: this.onSelectChange
  }
}

这里设置完, 可以实现点行选框, 但是点框选框就失灵了( 不是页面加载完毕的第一次点 )
这时只需要在监听选择事件里加入这些即可

this.options = {
   // alert: { clear: () => { this.selectedRowKeys = [] } },
   rowSelection: {
       selectedRowKeys: selectedRowKeys,
       onChange: this.onSelectChange
   }
 }
<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="规则编号">
              <a-input v-model="queryParam.id" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="使用状态">
              <a-select v-model="queryParam.status" placeholder="请选择" default-value="0">
                <a-select-option value="0">全部</a-select-option>
                <a-select-option value="1">关闭</a-select-option>
                <a-select-option value="2">运行中</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="调用次数">
                <a-input-number v-model="queryParam.callNo" style="width: 100%"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="更新日期">
                <a-date-picker v-model="queryParam.date" style="width: 100%" placeholder="请输入更新日期"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="使用状态">
                <a-select v-model="queryParam.useStatus" placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="1">关闭</a-select-option>
                  <a-select-option value="2">运行中</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="使用状态">
                <a-select placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="1">关闭</a-select-option>
                  <a-select-option value="2">运行中</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="$refs.createModal.add()">新建</a-button>
      <a-button type="dashed" @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }} alert</a-button>
      <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
          <!-- lock | unlock -->
          <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      :customRow="setRow"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="status" slot-scope="text">
        <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
      </span>

      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record)">配置</a>
          <a-divider type="vertical" />
          <a @click="handleSub(record)">订阅报警</a>
        </template>
      </span>
    </s-table>
    <create-form ref="createModal" @ok="handleOk" />
    <step-by-step-modal ref="modal" @ok="handleOk"/>
  </a-card>
</template>

<script type="text/ecmascript-6">
import moment from 'moment'
import { STable } from '@/components'
import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import { getRoleList, getServiceList } from '@/api/manage'

const statusMap = {
  0: {
    status: 'default',
    text: '关闭'
  },
  1: {
    status: 'processing',
    text: '运行中'
  },
  2: {
    status: 'success',
    text: '已上线'
  },
  3: {
    status: 'error',
    text: '异常'
  }
}

export default {
  name: 'TableList',
  components: {
    STable,
    CreateForm,
    StepByStepModal
  },
  data () {
    return {
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '#',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '规则编号',
          dataIndex: 'no'
        },
        {
          title: '描述',
          dataIndex: 'description'
        },
        {
          title: '服务调用次数',
          dataIndex: 'callNo',
          sorter: true,
          needTotal: true,
          customRender: (text) => text + ' 次'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '更新时间',
          dataIndex: 'updatedAt',
          sorter: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        return getServiceList(Object.assign(parameter, this.queryParam))
          .then(res => {
            return res.result
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    this.tableOption()
    getRoleList({ t: new Date() })
  },
  methods: {
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },

    handleEdit (record) {
      console.log(record)
      this.$refs.modal.edit(record)
    },
    handleSub (record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败,规则已关闭`)
      }
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.options = {
      // alert: { clear: () => { this.selectedRowKeys = [] } },
      rowSelection: {
          selectedRowKeys: selectedRowKeys,
          onChange: this.onSelectChange
        }
      }
      console.log('onselect之后', JSON.stringify(this.selectedRowKeys))
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    setRow (record) {
      return {
        on: {
          click: () => {
            let flag = false
            let keys = []
            keys = this.selectedRowKeys
            if(keys.indexOf(record.id) >= 0) {
                flag=true
            }
            if(flag){
               keys.splice(keys.findIndex(item => item === record.id), 1)
               this.selectedRows.splice(this.selectedRows.findIndex(item => item === record.id), 1)
            } else {
                keys.push(record.id)
                this.selectedRows.push(record)
            }
            this.options = {
           // alert: { clear: () => { this.selectedRowKeys = [] } },
            rowSelection: {
                selectedRowKeys: this.selectedRowKeys,
                onChange: this.onSelectChange
              }
            }
            console.log(flag)
            console.log(JSON.stringify(this.options.rowSelection.selectedRowKeys))
          }
        }
      }
    }
  }
}
</script>