vue实现移动按钮
Vue 实现移动按钮的方法
使用拖拽事件实现
在Vue中可以通过@mousedown、@mousemove和@mouseup事件实现按钮的拖拽移动效果。需要记录鼠标按下时的初始位置和元素当前的位置。
<template>
<div
class="draggable-btn"
:style="{ left: position.x + 'px', top: position.y + 'px' }"
@mousedown="startDrag"
>
拖拽我
</div>
</template>
<script>
export default {
data() {
return {
position: { x: 0, y: 0 },
isDragging: false,
startPos: { x: 0, y: 0 }
}
},
methods: {
startDrag(e) {
this.isDragging = true
this.startPos = {
x: e.clientX - this.position.x,
y: e.clientY - this.position.y
}
document.addEventListener('mousemove', this.onDrag)
document.addEventListener('mouseup', this.stopDrag)
},
onDrag(e) {
if (!this.isDragging) return
this.position = {
x: e.clientX - this.startPos.x,
y: e.clientY - this.startPos.y
}
},
stopDrag() {
this.isDragging = false
document.removeEventListener('mousemove', this.onDrag)
document.removeEventListener('mouseup', this.stopDrag)
}
}
}
</script>
<style>
.draggable-btn {
position: absolute;
width: 100px;
height: 40px;
background-color: #42b983;
color: white;
display: flex;
align-items: center;
justify-content: center;
cursor: move;
user-select: none;
}
</style>
使用第三方库实现
对于更复杂的拖拽需求,可以使用专门的拖拽库如vuedraggable或sortablejs。

安装vuedraggable:
npm install vuedraggable
使用示例:

<template>
<draggable v-model="list" @start="drag=true" @end="drag=false">
<div v-for="element in list" :key="element.id">
{{ element.name }}
</div>
</draggable>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: { draggable },
data() {
return {
list: [
{ name: "Item 1", id: 1 },
{ name: "Item 2", id: 2 }
]
}
}
}
</script>
移动端触摸事件支持
针对移动设备,需要使用触摸事件替代鼠标事件:
<template>
<div
class="draggable-btn"
:style="{ left: position.x + 'px', top: position.y + 'px' }"
@touchstart="startDrag"
@touchmove="onDrag"
@touchend="stopDrag"
>
拖拽我
</div>
</template>
<script>
export default {
data() {
return {
position: { x: 0, y: 0 },
isDragging: false,
startPos: { x: 0, y: 0 }
}
},
methods: {
startDrag(e) {
this.isDragging = true
const touch = e.touches[0]
this.startPos = {
x: touch.clientX - this.position.x,
y: touch.clientY - this.position.y
}
},
onDrag(e) {
if (!this.isDragging) return
const touch = e.touches[0]
this.position = {
x: touch.clientX - this.startPos.x,
y: touch.clientY - this.startPos.y
}
e.preventDefault()
},
stopDrag() {
this.isDragging = false
}
}
}
</script>
边界限制
可以为可移动元素添加边界限制,防止移出可视区域:
onDrag(e) {
if (!this.isDragging) return
let newX = e.clientX - this.startPos.x
let newY = e.clientY - this.startPos.y
// 限制在窗口范围内
const maxX = window.innerWidth - this.$el.offsetWidth
const maxY = window.innerHeight - this.$el.offsetHeight
newX = Math.max(0, Math.min(newX, maxX))
newY = Math.max(0, Math.min(newY, maxY))
this.position = { x: newX, y: newY }
}






