需求:
-
listA
克隆item
到listB
,listA
数据不变,更新listB
数据 -
listA
克隆过的不能再次克隆到listB
,需要先在listB
中删除克隆的数据 -
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>
效果如图