Sortable.js在Vue中拖拽后数据不更新怎么办?

誉馨(打工版) 阅读 12

我在用Sortable.js做列表拖拽排序,视图能动但data里的数组没变,这咋整?试过@change事件但好像没触发。

这是我的代码:

<template>
  <div ref="list" class="list">
    <div v-for="item in items" :key="item.id" class="item">
      {{ item.name }}
    </div>
  </div>
</template>

<script>
import Sortable from 'sortablejs';
export default {
  data() {
    return { items: [{ id: 1, name: 'A' }, { id: 2, name: 'B' }] };
  },
  mounted() {
    new Sortable(this.$refs.list, { animation: 150 });
  }
};
</script>
我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
技术光磊
你的问题是Sortable.js只做了DOM拖拽,根本没动你的data数组。这货不会自动同步数据,得手动来。

解决方法很简单,加上onEnd回调,在拖拽结束后手动更新数组:

import Sortable from 'sortablejs';

export default {
data() {
return {
items: [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' }
]
};
},
mounted() {
Sortable.create(this.$refs.list, {
animation: 150,
onEnd: (evt) => {
// 拖拽完成后手动调整数组顺序
const item = this.items.splice(evt.oldIndex, 1)[0];
this.items.splice(evt.newIndex, 0, item);
}
});
}
};


两个关键点:

一是用Sortable.create而不是new Sortable,这样更规范。

二是evt.oldIndex和evt.newIndex分别是拖拽元素原来的位置和放下的位置,用splice把元素从旧位置删掉,再插到新位置。

@change事件不是这么用的,那是Vue组件的绑定方式,Sortable用的是选项里的onChange或者onEnd回调。

这样搞完,拖拽完数组就会同步更新了。
点赞
2026-03-18 08:10