最近在把react项目使用vue3进行重构,vue项目组件库使用ant design vue。
重构的功能包括:
1,M站菜单配置列表的展示
2,菜单列表新增
3,菜单列表的编辑
4,列表的拖拽排序
阅读ant design vue文档看到有table拖拽功能,准备直接使用,此处埋下彩蛋一颗
。
顺利的重构了1,2,3功能之后,照着文档配置好拖拽属性发现不生效
,翻阅源码没有找到对应的配置代码,原来拖拽功能属于付费内容,一年4999,ops~(ps:支持知识付费哈~但是我穷)
那就只能自己手写功能4了
梳理思路如下:
1,鼠标移入table行,修改改行gragable=true,修改鼠标展示样式为move
2,添加dragstart事件,在该事件中记录sourceRecord数据
3,添加dragend事件,在该事件中记录targetRecord数据
4,整体list数据中交换这两条数据,更新list
ant design vue a-table提供了customRow属性
该属性可以对每一行添加对应的样式,事件,为我们的实现思路打开了缺口。
最后代码如下:
<a-table
:columns="columns"
:data-source="data"
:pagination="false"
:customRow="customRow"
@row-drag-end="onRowDragEnd"
>
<template #bodyCell="{ column, text, record }">
<template v-if="column.dataIndex === 'weight'">
{{ ++text }}
</template>
<template v-if="column.dataIndex === 'navName'">
<div :title="record.navName" class="overflowdiv">
{{ record.navName }}
</div>
</template>
<template v-if="column.dataIndex === 'iconUrl'">
<img class="appMenu-icon-img" :src="text" />
</template>
<template v-if="column.dataIndex === 'status'">
{{ text ? "已启用" : "未启用" }}
</template>
<template v-if="column.dataIndex === 'operatorName'">
<div :title="record.operatorName" class="overflowdiv">
{{ record.operatorName }}
</div>
</template>
<template v-if="column.dataIndex === 'updateTime'">
{{ text ? text : record.createTime }}
</template>
<template v-if="column.dataIndex === 'operation'">
<span class="appMenu-operation-span">
<span @click="() => this.handleEdit(record)"
>编辑<a-divider type="vertical"></a-divider
></span>
<span @click="() => handleEnableMenu(record)">{{
record.status ? "禁用" : "启用"
}}</span>
</span>
</template>
</template>
</a-table>
<script>
methods: {
customRow(record, index) {
console.log(record, index);
return {
style: {
cursor: "move",
},
// 鼠标移入
onMouseenter: (event) => {
// 兼容IE
var ev = event || window.event;
ev.target.draggable = true;
},
// 开始拖拽
onDragstart: (event) => {
// 兼容IE
var ev = event || window.event;
// 阻止冒泡
ev.stopPropagation();
// 得到源目标数据
this.sourceObj = record;
},
// 拖动元素经过的元素
onDragover: (event) => {
// 兼容 IE
var ev = event || window.event;
// 阻止默认行为
ev.preventDefault();
},
// 鼠标松开
onDrop: (event) => {
// 兼容IE
var ev = event || window.event;
// 阻止冒泡
ev.stopPropagation();
// 得到目标数据
this.targetObj = record;
console.log(this.sourceObj, this.targetObj);
const tempDta = this.data;
tempDta[this.targetObj.weight] = this.sourceObj;
tempDta[this.sourceObj.weight] = this.targetObj;
let weightList = [];
tempDta.forEach((item, index) => {
item.weight = index;
weightList.push({
id: item.id,
weight: index,
});
});
this.handleWeightModify(weightList);// 更改顺序接口
},
};
}
}
</script>
至此,拖拽排序table顺利重构完成。