Sortable.js在Vue中拖拽后数据不更新怎么办?
我在用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>
解决方法很简单,加上onEnd回调,在拖拽结束后手动更新数组:
两个关键点:
一是用Sortable.create而不是new Sortable,这样更规范。
二是evt.oldIndex和evt.newIndex分别是拖拽元素原来的位置和放下的位置,用splice把元素从旧位置删掉,再插到新位置。
@change事件不是这么用的,那是Vue组件的绑定方式,Sortable用的是选项里的onChange或者onEnd回调。
这样搞完,拖拽完数组就会同步更新了。