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

Vue Draggable跨容器拖拽失效问题排查求助

解决Vue Draggable跨容器拖拽失效的问题

嘿,我看到你的问题了——想把元素从一个容器拖到另一个却只能在原容器里移动对吧?这是因为你的代码里缺了两个关键配置,还有一处结构小问题,我来帮你一步步修复:

问题根源

  1. 缺少group属性配置:Vue Draggable默认每个组件都是独立的拖拽组,只有设置了相同group名称的组件之间,才能互相跨容器拖拽。
  2. Draggable组件结构错误:你把容器标题(<div class="heading">)放在了draggable标签内部,这会干扰拖拽组件的识别逻辑——它会把标题也当成可拖拽元素的一部分,导致拖拽行为异常。

修改后的完整代码

<template>
  <div id="app">
    <!-- LOG ALL DATA -->
    <button type="button" name="button" @click="showData()">show data</button>
    <div class="container">
      <!-- 把heading移到draggable外面,每个容器的结构更清晰 -->
      <div class="box-wrapper" v-for="(array, index) in numbers" :key="index">
        <div class="heading"> box {{ index + 1}} </div>
        <!-- 新增group属性,所有可跨拖的容器用同一个group名称 -->
        <draggable 
          :list="numbers[index]" 
          class="box"
          group="number-group"
        >
          <!-- 这里只放可拖拽的元素,每个元素要加key保证Vue列表渲染正确 -->
          <div class="box-data" v-for="(x, idx) in array" :key="idx"> {{ x }} </div>
        </draggable>
      </div>
    </div>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
export default {
  data(){
    return {
      numbers: [
        [1, 2, 3, 4, 5],
        [6, 7, 8],
        [9, 10, 11, 12]
      ],
    }
  },
  components: {
    draggable,
  },
  methods: {
    showData() {
      console.table(this.numbers);
    },
  }
}
</script>
<style>
#app{
  height: 100%;
}
html, body{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  height: 100%;
}
button{
  padding: 1rem;
  margin: 1rem;
  background-color: #984636;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.container{
  background-color: bisque;
  padding: 16px;
  margin: 16px;
  height: calc(100% - 100px); /* 调整高度避免按钮遮挡 */
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start; /* 改为flex-start让容器顶部对齐 */
  gap: 16px; /* 增加容器间距 */
}
.box-wrapper{
  width: 300px;
}
.box{
  min-height: 200px; /* 给容器设置最小高度,空容器也能看到 */
  background-color: pink;
  padding: 8px;
}
.box-data{
  padding: .5rem;
  margin: .5rem;
  background-color: #f6f7f8;
  border-radius: 4px;
  cursor: grab;
}
.box-data:active{
  cursor: grabbing;
}
.heading{
  text-align: center;
  margin-top: 1rem;
  font-weight: bold;
}
</style>

修改点说明

  • 添加group="number-group":所有需要互相拖拽的draggable组件必须使用同一个group名称,这样它们才会被识别为同一拖拽组,支持跨容器拖拽。
  • 调整DOM结构:把容器标题移到draggable组件外面,用box-wrapper包裹标题和拖拽容器,确保draggable内部只有可拖拽的box-data元素。
  • 优化样式:给box设置最小高度、给拖拽元素添加鼠标样式,提升交互体验;调整容器对齐方式避免布局错乱。

现在你再试试拖拽,就能把元素在三个容器之间自由移动了,点击"show data"按钮也能看到numbers数组的内容实时更新~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 11:07:35