Detailed usage of drag-and-drop plug-in sortablejs suitable for v2/v3

The three most commonly used drag-and-drop plug-ins on the market are:

Applicable to Vue3: vue.draggable.next   vue.draggable.next Chinese documentation - itxst.com

Applicable to Vue2: vue.draggable   vue.draggable Chinese documentation - itxst.com

Applicable to both V2/V3: sortableJs   sortable.js Chinese documentation - itxst.com

The above three Chinese documents have links to official documents.

I have introduced the mobile drag plug-in vue-draggable-next used by vue3 before. Today I will introduce sortableJS.

1. Download:

npm install sortablejs --save

 2.Introduce it to the page you need to use

import Sortable from "sortablejs";

3. Initialization and configuration items of 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");
        });
    },
  });
};

What I used above is to drag and drop the rows in the el-table. You can see that I also adjusted the backend interface inside the method to save the drag and drop order, and first used the following two lines of code to adjust the current There is a sequence of data,

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

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

However, after sortablejs is bound to a specific DOM, many people will find that although the order of the data has changed, the order of the data displayed on the page is chaotic . At this time, you can try to bind it. Add a unique key value to the dom element. If you use el-table like me, add row-key="id (this id must be a non-duplicate key name for each row in your tableData)"

Guess you like

Origin blog.csdn.net/SunFlower914/article/details/131658202