Vue使用Sortablejs拖拽排序 视图显示与数据不一致、拖拽结束后回跳问题
官网:Sortable.js中文网
注意:拖拽一定不能用index作为key,也不建议用item,否则会出现视图显示与数据不一致/回跳,建议用唯一值ID;
安装
npm install sortablejs --save
引入
import GapLine from '@/components/GapLine.vue';
使用
<template><!-- 菜单分组容器,ref用于获取DOM节点 --><view class="menu-group group-list" ref="sortGroupRef"><!-- 遍历显示菜单项,使用item作为key(实际开发建议用唯一ID) --><view class="menu-item flex-y-center" v-for="(item, index) in showList" :key="item" <!-- 注意:拖拽一定不能用index作为key,否则会回跳 -->><!-- 菜单项内容 -->{{ item }}</view></view>
</template><script>
// 引入拖拽排序库
import Sortable from 'sortablejs';export default {data() {return {// 菜单数据列表showList: ['自建菜单1', '自建菜单2', '自建菜单3', '自建菜单4'],}},// 生命周期:页面渲染完成时onReady() {// 等待下一个DOM更新周期,确保DOM已渲染this.$nextTick(() => {// 获取容器DOM节点(注意:uni-app中需要通过$el获取原生DOM)const sortEl = this.$refs.sortGroupRef.$el;// 初始化Sortable拖拽实例new Sortable(sortEl, {group: 'group-list', // 定义可拖拽组(允许多列表间拖拽)draggable: '.menu-item', // 指定可拖拽的子元素类名handle: '.sort-button', // 指定拖拽手柄元素类名(需在template中添加对应元素)animation: 200, // 拖拽动画时长(ms)// 拖拽结束回调onEnd: ({ newIndex, oldIndex }) => {// 获取被拖拽的元素const item = this.showList[oldIndex];// 从原位置删除元素this.showList.splice(oldIndex, 1);// 在新位置插入元素this.showList.splice(newIndex, 0, item);},});});},
}
</script>
注意:拖拽一定不能用index作为key,也不建议用item,否则会回跳,建议用唯一值ID;