Vue Draggable 拖拽后样式错乱怎么办?

皇甫志红 阅读 33

我用 Vue Draggable 做了一个可拖拽的列表,但拖动之后元素的宽度突然变窄了,看起来像是丢失了原有的 CSS 样式。明明没动过 class,也不报错,就是视觉上不对。

我试过给 draggable 元素加 key,也检查了 transition-group 的写法,但问题还在。是不是拖拽过程中某些样式被覆盖了?下面是我给列表项写的样式:

.drag-item {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  background: #f9f9f9;
  margin-bottom: 8px;
  box-sizing: border-box;
}
我来解答 赞 11 收藏
二维码
手机扫码查看
2 条解答
诺曦 ☘︎
Draggable 拖拽时会自动计算宽度并以内联样式覆盖你的 CSS。解决方法:给 draggable 组件加 style="{width: '100%'}",或者用 CSS 强制覆盖:

.sortable-ghost {
width: 100% !important;
}
.sortable-drag {
width: 100% !important;
}


这两个类分别是占位符和正在拖拽的元素,强制宽度就能搞定。
点赞
2026-03-20 11:18
公孙啸天
应该是拖拽时的 ghost 元素没继承样式。给 组件加个 ghost-class 属性,然后定义这个 class 的样式就行了。


  v-model="list"
item-key="id"
ghost-class="ghost-item"
>



.ghost-item {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
background: #f9f9f9;
margin-bottom: 8px;
box-sizing: border-box;
opacity: 0.5;
}


顺便检查一下你是不是把 class 写在了