You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置vue-draggable,拖动元素后不移除原列表对应元素?

解决vue-draggable拖动元素后原列表元素被移除的问题

要实现拖动列表A的元素到列表B时,列表A保留原元素,核心是把默认的移动操作改为复制操作,可以通过以下两种方式实现:

方法一:修改group配置为复制模式

vue-draggable的group配置中,将pull属性设为'clone'即可触发复制行为,而非默认的移动行为。同时要保证两个列表的group名称一致,且列表B的put属性设为true以允许接收元素。

修改后的列表A代码:

<div class="h-96 overflow-y-auto">
  <draggable 
    v-model="schema" 
    class="flex-col space-y-1" 
    :options="{
      sort: false, 
      ghostClass: 'ghost', 
      group: {
        name: 'schema', 
        pull: 'clone', // 设置为clone触发复制逻辑
        put: false
      }
    }"
  >
    <el-tag v-for="(item, index) in schema" :key="index">
      <span>{{ item.name ? `${item.name}(${item.column})` : item.column }}</span>
    </el-tag>
  </draggable>
</div>

列表B的对应配置示例:

<div class="h-96 overflow-y-auto">
  <draggable 
    v-model="targetList" 
    class="flex-col space-y-1" 
    :options="{
      sort: true, 
      ghostClass: 'ghost', 
      group: {
        name: 'schema', // 与列表A的group名称保持一致
        pull: true,
        put: true // 允许接收同组元素
      }
    }"
  >
    <el-tag v-for="(item, index) in targetList" :key="index">
      <span>{{ item.name ? `${item.name}(${item.column})` : item.column }}</span>
    </el-tag>
  </draggable>
</div>

方法二:自定义事件处理(适配复杂场景)

如果需要更灵活的逻辑控制,可以监听列表B的add事件,在元素被添加时手动恢复列表A的元素。这种方式适合需要额外处理元素的场景:

<!-- 列表B的配置 -->
<draggable 
  v-model="targetList" 
  @add="handleElementAdd"
  :options="{
    group: { name: 'schema', put: true }
  }"
>
  <!-- 标签内容 -->
</draggable>
// 事件处理函数
handleElementAdd(evt) {
  // 恢复列表A中被默认移除的元素
  this.schema.splice(evt.oldIndex, 0, evt.item);
  // 若元素是复杂对象,需深拷贝避免引用问题
  // const clonedItem = JSON.parse(JSON.stringify(evt.item));
  // this.targetList.splice(evt.newIndex, 1, clonedItem);
}

额外注意:

如果拖动的是复杂对象,使用pull: 'clone'默认是浅拷贝,若需要完全独立的副本,可以自定义clone函数:

group: {
  name: 'schema',
  pull: 'clone',
  clone: (item) => JSON.parse(JSON.stringify(item)) // 自定义深拷贝逻辑
}

内容的提问来源于stack exchange,提问作者user824624

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:12:53