v2/v3都适用的拖拽插件sortablejs详细使用方法

市面上使用比较多的三个拖拽插件有:

适用于Vue3:vue.draggable.next  vue.draggable.next 中文文档 - itxst.com

适用于Vue2:vue.draggable  vue.draggable中文文档 - itxst.com

V2/V3都适用:sortableJs  sortable.js中文文档 - itxst.com

以上三个中文文档中都有跳往官方文档的链接

之前有介绍过vue3使用的移动拖拽插件vue-draggable-next,今天介绍下sortableJS

1.下载:

npm install sortablejs --save

 2.在需要使用的页面引入

import Sortable from "sortablejs";

3. sortablejs的初始化及配置项

// 在页面dom元素挂载完成后初始化soratblejs
onMounted(() => {
  rowDrop();
});

// 定义方法初始化sortablejs并绑定配置项
const rowDrop = () => {
  const el = document.querySelector(".el-table__body tbody");
  Sortable.create(el, {
    animation: 150,
    ghostClass: "ghostClass", // 拖放占位符的类名
    chosenClass: "chosenClass", // 所选项的类名
    dragClass: "dragClass", // 拖拽对象移动样式
    handle: ".el-table__row",
    draggable: ".el-table__row", // 指定样式类的元素才允许拖动
    onEnd({ newIndex, oldIndex }) {
      // oldIIndex拖放前的位置, newIndex拖放后的位置
      if (props.tableData?.length < 2) return;
      
      // 修改排序数据
      const movedItem = props.tableData.splice(oldIndex, 1)[0];
      props.tableData.splice(newIndex, 0, movedItem);

      // 根据具体需求调接口保存排序数据
      let data = { currentKnwlgId: movedItem.pkId };
      props.tableData[newIndex + 1] &&
        (data.nextKnwlgId = props.tableData[newIndex + 1].pkId);
      props.tableData[newIndex - 1] &&
        (data.preKnwlgId = props.tableData[newIndex - 1].pkId);
      data.knwlgIdList = props.tableData.map((item) => item.pkId);
      changeKnwlgNodeRank(data)
        .then(() => {
          emits("getArtList");
          proxy.$modal.msgSuccess("拖拽成功!");
        })
        .catch(() => {
          emits("getArtList");
        });
    },
  });
};

上面我用到的是对el-table中的行做拖拽排序,大家可以看到我在方法内部还调了后端接口去保存拖拽的顺序,并且先使用了下面两行代码去调整现有数据的顺序,

const movedItem = props.tableData.splice(oldIndex, 1)[0];

props.tableData.splice(newIndex, 0, movedItem);

但在sortablejs绑定具体的dom后有不少人在使用的过程中会发现虽然数据的顺序发生了变化,但显示在页面上的数据顺序缺是乱的,此时大家可以尝试给绑定的dom元素加一个唯一的key值,如果像我一样使用el-table的话就加row-key="id(这个id必须是你tableData中每行row都有的且不重复的key名)"

猜你喜欢

转载自blog.csdn.net/SunFlower914/article/details/131658202