_makabaka

单选表格实现思路

element单选表格的实现,主要依靠elTable组件的 select 事件,假设存在如下表格:

以上面的表格为例子,可以通过如下步骤实现单选表格。

data

我们需要一个状态 tableData 用于存放表格的数据,还需要一个状态 selectedRow 用于存放当前勾选的行是数据。两个状态的默认值如下:

data() {
	return {
	  tableData: [], // 表格数据
	  selectedRow: null   // 当前选中行
	}
}

handleSelect

该方法是实现单选表格的核心方法,代码如下:

// 表格行勾选事件
handleSelect(selection, row) {
  // 判断是否存在选中元素
  if (selection.length === 0) {
	this.selectedRow = null
  } else {
	// 在selection中寻找row元素
	const { date } = row // 这里应该是用row的唯一的key
	const item = selection.find(i => i.date === date)
	if (item) {
	  // 找的到,说明本次是进行行勾选操作
	  this.selectedRow = row
	  // 取消全部勾选,然后单独勾选当前选中行
	  const table = this.$refs.table
	  table.clearSelection()
	  table.toggleRowSelection(row, true)
	} else {
	  // 找不到,说明本次是进行行取消勾选操作
	  this.selectedRow = null
	}
  }
}

代码思路都已经通过注释表明了,就不细说了。

tableTickEcho

表格勾选回显函数,这个方法是用来应对 selectedRow 存在默认值以及表格分页的情况。具体代码如下:

// 表格勾选回显
tableTickEcho() {
  const table = this.$refs.table
  // 因为是单选表格,尽可能不去全部遍历
  this.tableData.some(i => {
	if (i.date === this.selectedRow.date) {
	  table.toggleRowSelection(i, true)
	  return true
	}
  })
}

上面代码中的第6行,判断条件的key,需要根据实际情况去变更。

getTableData

获取表格数据,勾选回显方法就用在这里方法里。

// 获取表格数据
getTableData() {
  const list = [{
	date: '2016-05-02',
	name: '王小虎',
	address: '上海市普陀区金沙江路 1518 弄'
  }, {
	date: '2016-05-04',
	name: '王小虎',
	address: '上海市普陀区金沙江路 1517 弄'
  }]
  this.tableData = list
  // 判断是否需要回显
  if (!this.selectedRow) return
  // 避免出现未获取到实例的情况
  this.$nextTick(() => {
	this.tableTickEcho() // 表格勾选回显
  })
}

至此,功能方面已经完成。

样式问题

在element表格中,如果使用了 type=selection 的列,那么在表头会出现一个复选框。
image.png
这个复选框有着全选的语义,是不应该出现在单选表格中的,因此我们需要将其隐藏,一开始我的想法是用 slot=header 插槽去覆盖它,后来发现,当 type=selection 的时候,这个插槽并未其作用。[[element表格表头插槽源码阅读]]

进而考虑使用样式覆盖来将该复选框隐藏。

.el-table .el-table__header-wrapper th.el-table-column--selection.el-table__cell>.cell {
  display: none;
}

使得上面的css代码生效即可隐藏掉表格表头上的复选框,从而真正意义上完成一个单选表格。

posted on 2023-07-11 13:37  __makabaka  阅读(22)  评论(0编辑  收藏  举报

导航