我是怎么给Element UI的ElTable表头添加双击事件的

先介绍一个背景。需要双击表格的表头切换到编辑表头文本的模式。众所周知eltable没有暴露表头的插槽,我们想定制表头几乎不可能。我想过两种方案:

  1. 扩展eltable,使其支持表头插槽
  2. 拦截表头单击事件,触发双击事件

第一种显然是最灵活,最理想的方案。不过经过半个多小时的调研,我发现eltable的代码好复杂,骨肉相连呀,table.vue tabheheader.js tablecolumn.js store/helper.js store/index.js等等。短时间内我根本改不动!退而求其次吧,只要能识别出表头的双击事件,然后弹出一个对话框来修改表头吧。说干就干,下面是代码:

// 这段代码要写在Vue.use(Element)之前,写在main.js里面
const TableHeader = Element.Table.components.TableHeader;
const handleHeaderClick = TableHeader.methods.handleHeaderClick;
TableHeader.methods.handleHeaderClick = function(column, event) {
	if (this.clickedColumn && this.clickedColumn.id === column.id) {
		this.$parent.$emit('header-dbclick', column, event);
		this.timeout && clearTimeout(this.timeout);
		this.timeout = null;
		this.clickedColumn = null;
		return;
	}
	this.timeout && clearTimeout(this.timeout);
	this.timeout = setTimeout(() => {
		handleHeaderClick.call(this, column, event);
		this.timeout = null;
		this.clickedColumn = null;
	}, 300); // 300毫秒是我随手写的,可以根据自己的情况调整

	this.clickedColumn = column;
}

上面代码应该能跑起来,我是凭着记忆打出来的:)

上面代码有点问题,我还没有解决,就是如果连续点击超过2次,会触发双击事件和单击事件,如果表头开启了排序功能,会平白无故的启动一次排序,不太理想。要再调一下。不过大体思路是这样的。

真是好难过,上面的代码引入了一个bug,参考这里,解决办法是在el-table上添加drag-end事件

handleDragend(x,y,z, event) {
	setTimeout(() => {
		let target = event.target;
		while(target && target.tagName !== 'TH') {
			target = target.parentNode;
		}
		if (target) {
			target.classList.add('noclick');
		}
	}, 100);
}

帮助到你请点赞哦,嘻嘻

你可能感兴趣的:(前端之路)