2024.4.2今天我学习了如何对el-table表格组件实现内部横向拖拽的效果,效果:
代码如下:
一、创建utils/底下文件
const crosswise_drag_table = function (Vue){// 全局添加table左右拖动效果的指令Vue.directive('tableMove', {bind: function (el, binding, vnode) {let odiv = el // 获取当前表格元素// 修改样式小手标志// el.style.cursor = 'pointer'el.querySelector('.el-table .el-table__body-wrapper').style.cursor = 'pointer'let mouseDownAndUpTimer = nulllet mouseOffset = 0let mouseFlag = falselet bindRef = binding.value[0] //绑定的表格的ref属性odiv.onmousedown = (e) => {const ePath = composedPath(e)// 拖拽表头不滑动if (ePath.some(res => {return res && res.className && res.className.indexOf('el-table__header') > -1})) returnif (e.which !== 1) returnmouseOffset = e.clientXmouseDownAndUpTimer = setTimeout(function () {mouseFlag = true}, 80)}// odiv.onmouseup = (e) => {// setTimeout(() => {// // 解决拖动列宽行不对齐问题--渲染表格// vnode.context.$refs[bindRef].doLayout()// }, 200)// if (mouseFlag) {// mouseFlag = false// } else {// clearTimeout(mouseDownAndUpTimer) // 清除延迟时间// }// }// odiv.onmouseleave = (e) => {// setTimeout(() => {// // 解决拖动列宽行不对齐问题--渲染表格// vnode.context.$refs[bindRef].doLayout()// }, 200)// mouseFlag = false// }odiv.onmousemove = (e) => {if (e.which !== 1) returnconst divData = odiv.querySelector('.el-table .el-table__body-wrapper')if (mouseFlag && divData) {// 设置水平方向的元素的位置divData.scrollLeft -= (-mouseOffset + (mouseOffset = e.clientX))}}// 解决有些时候,在鼠标松开的时候,元素仍然可以拖动;odiv.ondragstart = (e) => {e.preventDefault()}odiv.ondragend = (e) => {e.preventDefault()}// 是否拖拽可选中文字odiv.onselectstart = () => {return false}//浏览器Event.path属性不存在function composedPath(e) {// 存在则直接returnif (e.path) {return e.path}// 不存在则遍历target节点let target = e.targete.path = []while (target.parentNode !== null) {e.path.push(target)target = target.parentNode}// 最后补上document和windowe.path.push(document, window)return e.path}}})
}export default crosswise_drag_table
二、在main.js中引入
// 横向拖拽表格
import crosswise_drag_table from '@/utils/crosswiseDragTable'Vue.use(crosswise_drag_table )
三、在vue文件中使用
<el-table ref='table_drag'v-table-move="['table_drag']"
></el-table>