vue实现一个拖拉拽 前端代码
时间: 2024-01-08 09:02:21 浏览: 154
好的,以下是一个简单的Vue拖拽组件实现:
```
<template>
<div class="drag-container">
<div class="drag-item" :style="{left: x + 'px', top: y + 'px'}" @mousedown="startDrag"></div>
</div>
</template>
<script>
export default {
data() {
return {
dragging: false,
x: 0,
y: 0,
initialX: 0,
initialY: 0,
xOffset: 0,
yOffset: 0
}
},
methods: {
startDrag(event) {
event.preventDefault()
this.initialX = event.clientX - this.xOffset
this.initialY = event.clientY - this.yOffset
if (event.target === this.$el.querySelector('.drag-item')) {
this.dragging = true
}
},
drag(event) {
event.preventDefault()
if (this.dragging) {
this.x = event.clientX - this.initialX
this.y = event.clientY - this.initialY
this.xOffset = this.x
this.yOffset = this.y
}
},
stopDrag() {
this.dragging = false
}
},
mounted() {
document.addEventListener('mousemove', this.drag)
document.addEventListener('mouseup', this.stopDrag)
},
beforeDestroy() {
document.removeEventListener('mousemove', this.drag)
document.removeEventListener('mouseup', this.stopDrag)
}
}
</script>
<style scoped>
.drag-container {
position: relative;
width: 500px;
height: 500px;
border: 1px solid #ccc;
}
.drag-item {
position: absolute;
width: 50px;
height: 50px;
background-color: #f00;
cursor: move;
}
</style>
```
这个组件包含一个可拖拽的红色方块,可以在其父容器内自由拖动。当鼠标按下时,开始拖动,移动时更新方块的位置,松开鼠标时结束拖拽。在mounted和beforeDestroy钩子中监听全局的mousemove和mouseup事件,以便在拖拽时不受限于方块的位置。
阅读全文