需求背景:有时候写公司企业历程需要按照手写的年份排序,但是企业历程又可能写成 xxx年以前,为了方便用户排序体验,使用表格拖拽排序。
使用了 sortablejs
2.安装
npm i sortablejs -s -d
3.使用
注意:<el-table></el-table>必须带有row-key="xx"这个属性,不然就会拖拽渲染表格出问题,这个问题就是你可能拖拽了,你看数据也变了,但是表格顺序没变,其实是因为表格渲染的时候,用了virtual-dom diff算法,(拖拽移动真实DOM -> 操作数据数组 -> Patch算法再更新真实DOM),具体参考博客https://www.jianshu.com/p/d92b9efe3e6a
HTML:
<el-tab-pane label="法律信息" name="sixth">
<el-table
:data="legalInfoList"
border
row-key="id" //一定要添加这个!!!
ref="legalInfoTable"
align="center"
>
<el-table-column label="排序" width="100px" align="center">
<template slot-scope="{}">
<img src="../../assets/otherSvg/drag.svg" alt style="width:16px;" />
</template>
</el-table-column>
<el-table-column
v-for="(item, i) in columns"
:key="i"
:prop="item.name"
:label="item.nameDesc"
align="center"
show-overflow-tooltip
></el-table-column>
//拖拽最好不要用fixed
<el-table-column label="操作" width="180">
<template slot-scope="scope">
<el-tooltip
content="编辑"
class="item"
effect="dark"
popper-class="table-tooltip"
placement="bottom"
>
<i
class="paifont pai-bianji on-table"
@click="editRow(scope,'legalInfo',legalInfoList)"
></i>
</el-tooltip>
<el-tooltip
content="删除"
class="item"
effect="dark"
popper-class="table-tooltip"
placement="bottom"
>
<i
class="paifont pai-guanbi on-table"
@click="delRow(scope,legalInfoList)"
></i>
</el-tooltip>
</template>
</el-table-column>
</el-table>
</el-tab-pane>
js:
import Sortable from "sortablejs";
data() {
return {
legalInfoSort:null, //这个必须写
legalInfoList:[],
}
}
mounted() {
this.rowDrop5();
},
methods: {
// 法律信息
rowDrop5() {
const that = this;
const el = this.$refs.legalInfoTable.$el.querySelectorAll(
".el-table__body-wrapper > table > tbody"
)[0];
this.rowDrapEx(el, this.legalInfoSort, 'legalInfoList');
},
// 公共拖拽方法
rowDrapEx(el, listSort, listType) {
const that = this;
listSort = Sortable.create(el, {
ghostClass: "sortable-ghost",
setData: function (dataTransfer) {
dataTransfer.setData("Text", "");
},
onEnd: (evt) => {
const targetRow = this[listype].splice(evt.oldIndex, 1)[0];
this[listype].splice(evt.newIndex, 0, targetRow);
},
});
},
//需要自己手动加一个唯一标识id
// 弹窗保存
followConform() {
this.$refs["ruleForm"].validate((valid) => {
if (valid) {
if (this.title == "新增") {
this.ruleForm.id = this.getOnlyId(5);
this.typeBox.push(Object.assign({}, this.ruleForm));
} else {
//编辑
this.typeBox.splice(
this.indexName,
1,
Object.assign({}, this.ruleForm)
);
}
this.dialogFormVisible = false;
} else {
return false;
}
});
},
// 前端生成唯一标识ID
getOnlyId(length) {
return Number(
Math.random().toString().substr(3, length) + Date.now()
).toString(36);
},
}
综上,记录一下使用过程,以备以后需要