我将 ekjcfn3902039 实现的核心细节放在这里,这样您就不必整理好 Pen 中发生的所有其他内容。全部功劳归于他/她。
- 将 SortableJS 添加到您的项目(通过 CDN 或通过 NMP 安装取决于您。)
- 将 SortableJS 导入到您的 .Vue 文件中。
- 将此功能添加到您的顶部
<script>区域:
function watchClass(targetNode, classToWatch) {
let lastClassState = targetNode.classList.contains(classToWatch);
const observer = new MutationObserver((mutationsList) => {
for (let i = 0; i < mutationsList.length; i++) {
const mutation = mutationsList[i];
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
const currentClassState = mutation.target.classList.contains(classToWatch);
if (lastClassState !== currentClassState) {
lastClassState = currentClassState;
if (!currentClassState) {
mutation.target.classList.add('sortHandle');
}
}
}
}
});
observer.observe(targetNode, { attributes: true });
}
- 将这些道具添加到您的 v-data-table def:
v-sortable-table="{onEnd:sortTheHeadersAndUpdateTheKey}"
:key="anIncreasingNumber"
- 添加此数据变量:
anIncreasingNumber: 1,
- 添加以下方法并将
this.tableHeaders更改为您的标头对象:
sortTheHeadersAndUpdateTheKey(evt) {
const headersTmp = this.tableHeaders;
const oldIndex = evt.oldIndex;
const newIndex = evt.newIndex;
if (newIndex >= headersTmp.length) {
let k = newIndex - headersTmp.length + 1;
while (k--) {
headersTmp.push(undefined);
}
}
headersTmp.splice(newIndex, 0, headersTmp.splice(oldIndex, 1)[0]);
this.table = headersTmp;
this.anIncreasingNumber += 1;
}
- 添加此指令:
directives: {
'sortable-table': {
inserted: (el, binding) => {
el.querySelectorAll('th').forEach((draggableEl) => {
// Need a class watcher because sorting v-data-table rows asc/desc removes the sortHandle class
watchClass(draggableEl, 'sortHandle');
draggableEl.classList.add('sortHandle');
});
Sortable.create(el.querySelector('tr'), binding.value ? { ...binding.value, handle: '.sortHandle' } : {});
},
},
}
我已在这支 Pen 中将其归结为最低限度:https://codepen.io/bradlymathews/pen/QWyXpZv?editors=1010