找了好多方式,通过css什么的没有实现,最后用样式选择搞定,可参考如下,以下是vue2写法
this.$nextTick(() => {
if (this.$refs.myTable) {
const headerWrapper = this.$refs.myTable.$el.querySelector('.el-table__header-wrapper');
headerWrapper.style.overflow = 'scroll';
headerWrapper.style.width = '100%';
// 设置 el-table__body-wrapper 的滚动条样式
// const bodyWrapper = this.$refs.myTable.$refs.bodyWrapper;
// if (bodyWrapper) {
// bodyWrapper.style.overflow = 'auto'; // 确保滚动条出现
// bodyWrapper.style.scrollbarWidth = 'thin'; // 设置滚动条为细滚动条
// bodyWrapper.style.scrollbarColor = '#ddd' // 设置滚动条颜色
// }
// 设置 el-table__header-wrapper 的滚动条样式
if (headerWrapper) {
headerWrapper.style.overflow = 'auto'; // 确保滚动条出现
headerWrapper.style.scrollbarWidth = 'thin'; // 设置滚动条为细滚动条
headerWrapper.style.scrollbarColor = '#ddd' // 设置滚动条颜色
}
if (headerWrapper) {
headerWrapper.addEventListener('scroll', (event) => {
if (this.$refs.myTable) {
const target = event.target;
this.$refs.myTable.$refs.bodyWrapper.scrollLeft = target.scrollLeft;
}
})
}
}
})
ref="myTable"
效果如图
vue3 写法
nextTick(() => {
if (tableRef.value) {
const headerWrapper = tableRef.value.$el.querySelector('.el-table__header-wrapper');
if (headerWrapper) {
headerWrapper.style.overflow = 'auto'; // 确保滚动条出现
headerWrapper.style.scrollbarWidth = 'thin'; // 设置滚动条为细滚动条
headerWrapper.style.scrollbarColor = '#ddd'; // 设置滚动条颜色
// 确保 bodyWrapper 已渲染
nextTick(() => {
const bodyWrapper = tableRef.value.$el.querySelector('.el-scrollbar__wrap--hidden-default');
if (bodyWrapper) {
headerWrapper.addEventListener('scroll', (event) => {
nextTick(() => {
bodyWrapper.scrollLeft = event.target.scrollLeft;
});
});
}
});
}
}
});
})