SortableJS vue3 两个列表拖拽

需求:

  1. listA 克隆 itemlistBlistA数据不变,更新 listB数据
  2. listA 克隆过的不能再次克隆到 listB,需要先在 listB中删除克隆的数据
  3. listB 不能拖动到 listA
<template>
  <div class="box">
    <div class="item" id="LA" :key="randomKey">
      <p :class="{ filtered: item.flag }" v-for="item in listA" :key="item.id">{{ item.name }}{{ item.flag }}</p>
    </div>
    <div class="item" id="LB">
      <p v-for="(item, index) in listB" :key="item.id">
        {{ item.name }}{{ item.flag }}
        <button @click="remove(item, index)">删除</button>
      </p>
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue';
import Sortable from 'sortablejs';

let listA = ref([
  { id: 1, name: '张三', flag: false },
  { id: 2, name: '李四', flag: false },
  { id: 3, name: '王五', flag: false },
  { id: 4, name: '赵六', flag: false }
]);

let listB = ref([]);

let randomKey = ref(Math.random());

onMounted(() => {
  bindSortable();
});

const bindSortable = () => {
  new Sortable(LA, {
    group: {
      name: 'shared',
      pull: 'clone',
      put: false // 不允许拖拽进这个列表
    },
    animation: 150,
    filter: '.filtered',
    sort: false, // 设为false,禁止sort,
    // 结束拖拽
    onEnd: function (evt) {
      if (evt.to.id == 'LB') {
        const { oldIndex, newIndex } = evt;

        listA.value[oldIndex].flag = true;

        const movedItem = JSON.parse(JSON.stringify(listA.value[oldIndex]));
        listB.value.splice(newIndex, 0, { ...movedItem });
        reDrawer();
      }
    }
  });

  new Sortable(LB, {
    group: 'shared',
    animation: 150,
    onAdd: function (evt) {
      evt.item.remove();
    },
    onEnd: function (evt) {
      const { oldIndex, newIndex } = evt;
      console.log(oldIndex, newIndex);

      const movedItem = listB.value.splice(oldIndex, 1)[0];
      listB.value.splice(newIndex, 0, movedItem);
    }
  });
};

// 重排
const reDrawer = () => {
  randomKey.value = Math.random();
  nextTick(() => {
    bindSortable();
  });
};

const remove = (item, index) => {
  console.log(item, index);
  listA.value.find((v) => v.id == item.id).flag = false;
  listB.value.splice(index, 1);
};
</script>

<style lang="less" scoped>
.box {
  display: flex;
  .item {
    width: 300px;
    height: 200px;
    border: 1px solid #dedede;
    p {
      cursor: pointer;
    }
  }
}
</style>

效果如图


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容