vue实现印章拖拽效果
Vue 实现印章拖拽效果
使用 Vue Draggable 库
安装 vuedraggable 库:
npm install vuedraggable --save
引入并注册组件:
import draggable from 'vuedraggable';
export default {
components: { draggable },
data() {
return {
stamps: [
{ id: 1, text: "印章1", x: 50, y: 50 },
{ id: 2, text: "印章2", x: 150, y: 150 }
]
};
}
};
模板中使用:

<draggable
v-model="stamps"
@start="onDragStart"
@end="onDragEnd"
:options="{ handle: '.stamp-handle' }">
<div v-for="stamp in stamps" :key="stamp.id" class="stamp">
<div class="stamp-handle">{{ stamp.text }}</div>
</div>
</draggable>
自定义拖拽实现
通过 Vue 的 @mousedown、@mousemove 和 @mouseup 事件实现基础拖拽:
export default {
data() {
return {
stamps: [
{ id: 1, text: "印章", x: 0, y: 0, isDragging: false }
],
dragStart: { x: 0, y: 0 }
};
},
methods: {
startDrag(stamp, event) {
stamp.isDragging = true;
this.dragStart.x = event.clientX - stamp.x;
this.dragStart.y = event.clientY - stamp.y;
},
onDrag(stamp, event) {
if (stamp.isDragging) {
stamp.x = event.clientX - this.dragStart.x;
stamp.y = event.clientY - this.dragStart.y;
}
},
stopDrag(stamp) {
stamp.isDragging = false;
}
}
};
模板部分:

<div
v-for="stamp in stamps"
:key="stamp.id"
class="stamp"
:style="{ left: stamp.x + 'px', top: stamp.y + 'px' }"
@mousedown="startDrag(stamp, $event)"
@mousemove="onDrag(stamp, $event)"
@mouseup="stopDrag(stamp)"
@mouseleave="stopDrag(stamp)">
{{ stamp.text }}
</div>
样式优化
为印章添加基础样式:
.stamp {
position: absolute;
width: 100px;
height: 100px;
border: 2px dashed #ccc;
display: flex;
align-items: center;
justify-content: center;
cursor: move;
user-select: none;
background-color: rgba(255, 0, 0, 0.2);
border-radius: 50%;
}
边界限制
防止拖拽超出容器范围:
onDrag(stamp, event) {
if (stamp.isDragging) {
const container = this.$el.getBoundingClientRect();
const maxX = container.width - 100; // 印章宽度
const maxY = container.height - 100;
stamp.x = Math.max(0, Math.min(event.clientX - this.dragStart.x, maxX));
stamp.y = Math.max(0, Math.min(event.clientY - this.dragStart.y, maxY));
}
}
触摸屏适配
添加触摸事件支持:
<div
@touchstart="startDrag(stamp, $event.touches[0])"
@touchmove="onDrag(stamp, $event.touches[0])"
@touchend="stopDrag(stamp)">
</div>






