Sortable.js 拖拽后数据没更新怎么办?
我用 Sortable.js 做了个列表拖拽排序,视觉上能拖动,但背后的数组数据没跟着变,这咋整?
我试过在 onEnd 回调里手动 splice 调整数组,但顺序总是不对,是不是哪里搞错了?
const sortable = new Sortable(listEl, {
onEnd: (evt) => {
const { oldIndex, newIndex } = evt;
const item = myArray.splice(oldIndex, 1)[0];
myArray.splice(newIndex, 0, item);
}
});
oldIndex和newIndex是 DOM 索引,但你数组里删掉一个再插回去时索引已经变了,应该先保存原始索引再操作:等等,你这代码本身逻辑没错啊……那可能是你
myArray不是响应式数据?Vue 里得用this.$set或者直接替换整个数组才能触发更新,React 里得用setList([...newArr]),你要是直接改原数组可能视图不刷新。应该能用,但得确认下你用的是什么框架。