使用 sortable.js 时, 固定列表顶部和底部(不能修改顺序)
原理
- 先设置顶部和底部的选项不可被拖动(通过 sortable.create 的参数 handle, filter 实现), 并记录中间可移动区域的 index 范围(上限, 下限)
- 利用 sortable 配置的 onEnd 函数和 sortable 实例的 toArray 方法, 暂存移动前的顺序
- 移动完成后, 若发现被移动项新位置超出了允许移动区域, 则使用 sortable 实例的 sort 方法, 传入移动前顺序数组, 按移动前顺序重新排列
代码
endFunc(e) {
if (e.newIndex !== e.oldIndex) {
let sortedArr = this.sortInstance.toArray();
sortedArr.splice(e.oldIndex, 0, ...sortedArr.splice(e.newIndex, 1));
if (e.newIndex >= this.boundEnd) {
this.sortInstance.sort(sortedArr);
} else {
this.list_options.splice(e.newIndex, 0, ...this.list_options.splice(e.oldIndex, 1));
}
}
}