My implementation involves using a table component from Element UI and creating a custom method for enabling drag-and-drop functionality:
initializeDragAndDropFunctionality() {
const tableColumn = this.$refs.tableRef.$el.querySelector(
'.el-table__header-wrapper .el-table__header thead tr'
);
Sortable.create(tableColumn, {
draggable: 'th',
onEnd: this.dragReorderColumn
});
}
This method is called when the Component mounts:
mounted() {
this.initializeTable();
},
In order to make it work, you must assign a value to the "ref" attribute in the table:
<el-table
ref="tableRef"
>
<el-table-column
v-for="(column, index) in tableTitles"
:label="column.title"
:prop="column.field"
:width="column.width"
>
</el-table-column>
</el-table>
The component also imports a utility class that leverages Sortablejs library:
import Sortable from 'sortablejs';
const vueSortable = {
...Sortable,
create(el, options) {
function swap(draggableSelector, movedElement, oldIndex, newIndex) {
const parent = movedElement.parentNode;
const cells = parent.querySelectorAll(draggableSelector);
if (oldIndex > newIndex) {
parent.insertBefore(movedElement, cells[newIndex]);
} else {
parent.insertBefore(movedElement, cells[newIndex].nextSibling);
}
}
const tmpStorage = {};
const newOptions = {
...options,
onEnd(evt) {
swap(options.draggable, evt.item, evt.newIndex, evt.oldIndex);
tmpStorage.onChange = undefined;
if (options.onEnd) {
try {
options.onEnd(evt);
} catch (ex) {
console.error('Error at onEnd:', ex);
}
}
}
};
return Sortable.create(el, newOptions);
}
};
export default vueSortable;