JavaScript

js拖动排序功能

2022-07-28  本文已影响0人  剑指流云

拖动后直接更新数据到服务端即可,如果是vue,则需要设置key,请不要使用index作为key,如果是element-ui的table,则需要设置row-key属性,rowDrop方法需要在mounted生命周期函数中调用

import Sortable from "sortablejs";
// 行拖拽
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        //  指定父元素下可被拖拽的子元素
        draggable: ".el-table__row",

        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0];
          _this.tableData.splice(newIndex, 0, currRow);
          // 调后台拖拽排序接口
          _this._updateMoveData(newIndex, oldIndex, currRow);
        },
      });
    },
  },
// 拖拽更新接口
    _updateMoveData(nIndex, oIndex, crow) {
      if (nIndex == oIndex) return;
      let list = this.tableData.map((item, index) => {
        return { id: item.pk, show_id: ++index };
      });
      this.$axios.post("/admin/banner/sequence", { list }).then((res) => {
        if (res.code == 1) {
          this.$message.success("调整成功");
        }
      });
    },
上一篇 下一篇

猜你喜欢

热点阅读