当界面只有一个el-table的时候可以直接使用height属性来固定高度,但是如果界面中有多个el-table且上下排布时,就可能会用到拖拽改变table高度来隐藏一部分不需要的信息,下面就直接上代码:
// 函数节流
function throttle (fn, interval = 100) {
let timer = null;
let firstTime = true;
return function (...args) {
if (firstTime) {
// 第一次加载
fn.apply(this, args);
firstTime = false;
return;
}
if (timer) {
// 定时器正在执行中,跳过
return;
}
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
fn.apply(this, args);
}, interval);
};
}
export default {
name: 'dragTable',
inserted (el) {
/* 垂直调整 cursor: s-resize */
let mouseMove; // 定义变量保存el鼠标移动事件,用于重新绑定
mouseMove = el.onmousemove = (e) => {
const clientRect = el.getBoundingClientRect();
const x = e.clientX;
const y = e.clientY;
// 当鼠标移动到该table底部的时候出现垂直拖动图标
if ((clientRect.top + clientRect.height - 2 <= y && clientRect.top + clientRect.height + 4 >= y) && clientRect.left + 10 < x && clientRect.left + clientRect.width - 10 > x) {
el.style.cursor = 's-resize';
el.onmousedown = () => {
throttle(document.onmousemove = (e) => {
const y = e.clientY;
const tBody = el.querySelector('.el-table__body-wrapper');
const fBody = el.querySelector('.el-table__fixed-body-wrapper'); // 获取el-table的fixed固定栏的body-wrapper
const clientRect = tBody.getBoundingClientRect();
tBody.style.height = `${y - clientRect.top}px`;
// 此处需要判断是否有fixed属性,否则无该属性时会报错
fBody && (fBody.style.height = `${y - clientRect.top - 12}px`);
});
// 事件解绑
document.onmouseup = (e) => {
el.onmousemove = mouseMove;
el.onmousedown = null;
document.onmouseup = null;
document.onmousemove = null;
};
};
} else {
el.style.cursor = 'auto';
el.onmousedown = null;
}
};
}
};