element ui table中使用拖拽排序组件sortablejs及注意事项
1.使用:
先安装 sortablejs
插件,然后在当前页面引入
npm install sortablejs --save
import Sortable from "sortablejs";
具体代码如下:
<el-table class="sortingVisible" :data="tableData" row-key="id" v-loading="loading">
<el-table-column label="公司" prop="declareUnit"></el-table-column>
<el-table-column label="议题标题" prop="title"></el-table-column>
</el-table>
// An highlighted block
<script>
import Sortable from "sortablejs";
export default {
name: "SortingDialog",
components: {
Sortable,
},
data() {
return {
tableData: [],
loading:true
};
},
created() {
},
mounted() {
let _this = this;
_this.$nextTick(() => {
_this.rowDrop();
});
},
methods: {
rowDrop() {
const tbody = document.querySelector(".sortingVisible .el-table__body-wrapper tbody");
const _this = this;
Sortable.create(tbody, {
onEnd({
newIndex, oldIndex }) {
const currRow = _this.tableData.splice(oldIndex, 1)[0]; //当前行
_this.tableData.splice(newIndex, 0, currRow);
console.log(_this.tableData) //_this.tableData是拖拽后的表格数据,可直接提交到后端
},
});
}
}
};
</script>
2.注意事项:
(1)el-table标签上必须带上row-key=" ",否则拖拽不生效;如图:
(2)当table是嵌套在el-dialog等组件中,并且父组件中包含其他table时,直接使用 document.querySelector(".el-table__body-wrapper tbody")时会拿到父组件的tbody元素,所以需要给个标识(类名)来拿我们所需要的tbody。如图: