在vue项目中 列表的拖拽排序

3,474 阅读5分钟

一、draggable 原生拖拽

<div v-for="(item, index) in aiInfoConData"
    :key="item"
    class="aiInfoConItem"
    :draggable="true"  //可以拖拽
    @dragstart="dragstart(item, index)"
    @dragenter="dragenter(item, index)"
    @dragend="dragend(item, index)"
    >  
    {{item}}
</div>
const clickVal = ref<string>();
const moveVal = ref<string>();
const endVal = ref<string>();

const dragstart = (val, index1) => {
  console.log(val, index1, '11111');
  clickVal.value = val;
};

const dragenter = (val, index1) => {
  console.log(val, index1, '2222');
  moveVal.value = val;
};
const dragend = (val, index1) => {
  console.log(val, index1, '3333');
  endVal.value = val;
  const index = aiInfoConData.value.indexOf(val);
  const moveObj = moveVal.value ? moveVal.value : '';
  const addIndex = aiInfoConData.value.indexOf(moveObj);
  aiInfoConData.value.splice(index, 1);
  aiInfoConData.value.splice(addIndex, 0, val);
};

二、使用 Sortable 组件

sortablejs.com/

安装: npm i sortablejs --save

引入: import Sortable from 'sortablejs';

  • 父级设置id
  • 循环遍历中添加 @mouseenter="tipEnter(item.id)" @mouseleave="tipShow = false"
  <div id="dragcon" ref="containerBoxScrool" style="padding-top: 20px"> 
    <div
      v-for="(item, index) in aiInfoConData"
      :key="item"
      class="aiInfoConItem sort-btn relative cursor-default"
      @mouseenter="tipEnter(item.id)"
      @mouseleave="tipShow = false"
    >
        {{item}}
    </div> 
  </div>
const tipId = ref(0);
const tipEnter = id => {
  tipId.value = id; //如果有需要添加id
};
const initSortable = () => {
  const el = document.getElementById('dragcon');
  // 创建拖拽实例
  Sortable.create(el, {
    animation: 150,
    handle: '.sort-btn',
    dragClass: 'sort-active',
    chosenClass: 'sort-active',
    dataIdAttr: 'id',
    // 结束拖动事件
    onEnd: ({ newIndex, oldIndex }) => {
    //拖动后的操作
      const curr = JSON.parse(JSON.stringify(aiInfoConData.value[oldIndex]));
      nextTick(() => {
        aiInfoConData.value.splice(oldIndex, 1);
        aiInfoConData.value.splice(newIndex, 0, curr);
      });

      const params = {
        id: curr.id,
        index: newIndex
      };
      const response: any = writeApi.aiInfo.moveTemp(params);
      if (response?.data?.code === '0000') {
        ElMessage.success('移动成功');
      }

      // 调后端接口。。。。。。
    }
  });
};
onMounted(() => {
  nextTick(() => {
    initSortable();
  }); 
});

配置项:

var sortable = new Sortable(el, {
    group: "name",  // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
    sort: true,  // boolean 定义是否列表单元是否可以在列表容器内进行拖拽排序
    delay: 0, // number 定义鼠标选中列表单元可以开始拖动的延迟时间;
    touchStartThreshold: 0, // px, how many pixels the point should move before cancelling a delayed drag event
    disabled: false, // boolean 定义是否此sortable对象是否可用,为true时sortable对象不能拖放排序等功能,为false时为可以进行排序,相当于一个开关;
    store: null,  // @see Store
    animation: 150,  // ms, number 单位:ms,定义排序动画的时间
    easing: "cubic-bezier(1, 0, 0, 1)", // Easing for animation. Defaults to null. See https://easings.net/ for examples.
    handle: ".my-handle",  // 格式为简单css选择器的字符串,使列表单元中符合选择器的元素成为拖动的手柄,只有按住拖动手柄才能使列表单元进行拖动
    filter: ".ignore-elements",  // 过滤器,不需要进行拖动的元素
    preventOnFilter: true, //  在触发过滤器`filter`的时候调用`event.preventDefault()`
    draggable: ".item",  // 允许拖拽的项目类名
    ghostClass: "sortable-ghost",  // drop placeholder的css类名
    chosenClass: "sortable-chosen",  // 被选中项的css 类名
    dragClass: "sortable-drag",  // 正在被拖拽中的css类名
    dataIdAttr: 'data-id',

    swapThreshold: 1, // Threshold of the swap zone
    invertSwap: false, // Will always use inverted swap zone if set to true
    invertedSwapThreshold: 1, // Threshold of the inverted swap zone (will be set to swapThreshold value by default)
    direction: 'horizontal', // 拖拽方向 (默认情况下会自动判断方向)

    forceFallback: false,  // 忽略 HTML5拖拽行为,强制回调进行

    fallbackClass: "sortable-fallback",  // 当使用forceFallback的时候,被复制的dom的css类名
    fallbackOnBody: false,  // 将cloned DOM 元素挂到body元素上。
    fallbackTolerance: 0, // Specify in pixels how far the mouse should move before it's considered as a drag.

    scroll: true, // or HTMLElement
    scrollFn: function(offsetX, offsetY, originalEvent, touchEvt, hoverTargetEl) { ... }, // if you have custom scrollbar scrollFn may be used for autoscrolling
    scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
    scrollSpeed: 10, // px
    bubbleScroll: true, // apply autoscroll to all parent elements, allowing for easier movement

    dragoverBubble: false,
    removeCloneOnHide: true, // Remove the clone element when it is not showing, rather than just hiding it
    emptyInsertThreshold: 5, // px, distance mouse must be from empty sortable to insert drag element into it


    setData: function (/** DataTransfer */dataTransfer, /** HTMLElement*/dragEl) {
    dataTransfer.setData('Text', dragEl.textContent); // `dataTransfer` object of HTML5 DragEvent
    },

    // 元素被选中
    onChoose: function (/**Event*/evt) {
    evt.oldIndex;  // element index within parent
    },

    // 元素未被选中的时候(从选中到未选中)
    onUnchoose: function(/**Event*/evt) {
    // same properties as onEnd
    },

    // 开始拖拽的时候
    onStart: function (/**Event*/evt) {
    evt.oldIndex;  // element index within parent
    },

    // 结束拖拽
    onEnd: function (/**Event*/evt) {
    var itemEl = evt.item;  // dragged HTMLElement
    evt.to;    // target list
    evt.from;  // previous list
    evt.oldIndex;  // element's old index within old parent
    evt.newIndex;  // element's new index within new parent
    evt.clone // the clone element
    evt.pullMode;  // when item is in another sortable: `"clone"` if cloning, `true` if moving
    },

    // 元素从一个列表拖拽到另一个列表
    onAdd: function (/**Event*/evt) {
    // same properties as onEnd
    },

    // 列表内元素顺序更新的时候触发
    onUpdate: function (/**Event*/evt) {
    // same properties as onEnd
    },

    // 列表的任何更改都会触发
    onSort: function (/**Event*/evt) {
    // same properties as onEnd
    },

    // 元素从列表中移除进入另一个列表
    onRemove: function (/**Event*/evt) {
    // same properties as onEnd
    },

    // 试图拖拽一个filtered的元素
    onFilter: function (/**Event*/evt) {
    var itemEl = evt.item;  // HTMLElement receiving the `mousedown|tapstart` event.
    },

    // 拖拽移动的时候
    onMove: function (/**Event*/evt, /**Event*/originalEvent) {
    // Example: https://jsbin.com/nawahef/edit?js,output
    evt.dragged; // dragged HTMLElement
    evt.draggedRect; // DOMRect {left, top, right, bottom}
    evt.related; // HTMLElement on which have guided
    evt.relatedRect; // DOMRect
    evt.willInsertAfter; // Boolean that is true if Sortable will insert drag element after target by default
    originalEvent.clientY; // mouse position
    // return false; — for cancel
    // return -1; — insert before target
    // return 1; — insert after target
    },

    // clone一个元素的时候触发
    onClone: function (/**Event*/evt) {
    var origEl = evt.item;
    var cloneEl = evt.clone;
    },

    // 拖拽元素改变位置的时候
    onChange: function(/**Event*/evt) {
    evt.newIndex // most likely why this event is used is to get the dragging element's current index
    // same properties as onEnd
    }
});

eg

    <div id="dragcon" ref="containerBoxScrool" style="padding-top: 20px">
            <div
              v-for="(item, index) in aiInfoConData"
              :key="item"
              v-loading="item.templateId == '基金行情图' && funTuLoading"
              class="aiInfoConItem sort-btn relative cursor-default"
              @mouseenter="tipEnter(item.id)"
            >
              <div class="upDown"></div>
              <div class="inpCon">
                <div class="inpConTextBox">
                  <span class="badgeClass">{{ formattedIndex(Number(index) + 1) }}</span>
                  <el-icon class="closeClass" @click="delCon(item)"><Close /></el-icon>
                  <!-- <el-tooltip effect="dark" content="可长按拖动排序" placement="top-start">
                    <el-icon class="sortClass" @click="delCon(item)"><Sort /></el-icon>
                  </el-tooltip> -->
                  <BasicEditor
                    v-if="item.type != '1'"
                    v-model:value="item.resultContent"
                    :simple="true"
                    :default-id="item.id"
                    :height="240"
                    :disabled="tuoFlag"
                    @change="
                      e => {
                        contentChange(e, item);
                      }
                    "
                  ></BasicEditor>
                  <span v-if="item?.type != '1' && item.resultContent?.length" class="inpConTextLength">
                    字数:{{ getTextLength(item.resultContent) }}
                  </span>
                </div>

                <div v-if="item.type == '1'" class="ImgBox">
                  <imgUploadComponent
                    v-model="item.resultContent"
                    :del-flag="true"
                    @click="imgClick(item)"
                    @imgChange="
                      e => {
                        imgChange(e, item);
                      }
                    "
                  ></imgUploadComponent>
                </div>
              </div>
              <div class="aiInfoConItemGen">
                <el-tree-select
                  v-if="item.type == '0'"
                  v-model="item.templateId"
                  :data="treeData"
                  :render-after-expand="false"
                  placeholder="请选择模板"
                  style="width: 80%; display: inlie-block; margin: 0 0 10px"
                  @change="
                    e => {
                      tempChange(e, item);
                    }
                  "
                />
                <el-button
                  v-if="item.type == '0'"
                  :disabled="!item.templateId"
                  type="primary"
                  size="small"
                  style="margin-right: 10px"
                  @click="generateCon(item)"
                >
                  生成
                </el-button>

                <el-select
                  v-if="item.type == '1'"
                  v-model="item.templateId"
                  style="width: 80%; display: inlie-block; margin: 0 0 10px"
                  placeholder="请选择类型"
                  @change="
                    e => {
                      imgTypeChange(e, item);
                    }
                  "
                >
                  <el-option v-for="(opt, index) in imgTypeList" :key="index" :label="opt.name" :value="opt.dictId" />
                </el-select>
                <el-select
                  v-if="item.type == '2'"
                  v-model="item.templateId"
                  style="width: 80%; display: inlie-block; margin: 0 0 10px"
                  placeholder="请选择类型"
                  @change="
                    e => {
                      partTypeChange(e, item);
                    }
                  "
                >
                  <el-option v-for="(opt, index) in partTypeList" :key="index" :label="opt.name" :value="opt.dictId" />
                </el-select>
                <el-button
                  v-if="item.type != '0'"
                  type="success"
                  size="small"
                  style="margin-right: 10px"
                  @click="generateUpdate(item, index)"
                >
                  刷新
                </el-button>
              </div>
            </div>
          </div>
          
          
import Sortable from 'sortablejs';     
          
const initSortable = () => {
  const el = document.getElementById('dragcon');
  // 创建拖拽实例
  Sortable.create(el, {
    animation: 100,
    swapThreshold: 1,
    handle: '.badgeClass',
    dragClass: 'sort-active',
    chosenClass: 'sort-active',
    dataIdAttr: 'id',

    onStart() {
      tuoFlag.value = true;
    },
    // 结束拖动事件
    onEnd: ({ newIndex, oldIndex }) => {
      tuoFlag.value = false;
      const curr = JSON.parse(JSON.stringify(aiInfoConData.value[oldIndex]));
      nextTick(() => {
        aiInfoConData.value.splice(oldIndex, 1);
        aiInfoConData.value.splice(newIndex, 0, curr);
      });

      const params = {
        id: curr.id,
        index: newIndex
      };
      const response: any = writeApi.aiInfo.moveTemp(params);
      if (response?.data?.code === '0000') {
        ElMessage.success('移动成功');
      }

      // 调后端接口。。。。。。
    }
  });
};
onMounted(() => {
  nextTick(() => {
    initSortable();
  });
})