在Vue中实现一个可拖拽移动的悬浮球可以通过组合API和原生DOM事件来完成。以下是一个简单的示例:
<template>
<div id="app">
<div
class="draggable"
:style="{ top: ballPosition.y + 'px', left: ballPosition.x + 'px' }"
@mousedown="handleMouseDown"
@touchstart="handleTouchStart"
>
拖动我
</div>
</div>
</template>
<script>
import { reactive, toRefs } from 'vue';
export default {
setup() {
const state = reactive({
isDragging: false,
ballPosition: { x: 0, y: 0 },
});
const handleMouseMove = (event) => {
if (state.isDragging) {
state.ballPosition.x = event.clientX - 25;
state.ballPosition.y = event.clientY - 25;
}
};
const handleMouseUp = () => {
state.isDragging = false;
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
const handleMouseDown = (event) => {
state.isDragging = true;
handleMouseMove(event);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
const handleTouchMove = (event) => {
if (state.isDragging) {
state.ballPosition.x = event.touches[0].clientX - 25;
state.ballPosition.y = event.touches[0].clientY - 25;
}
};
const handleTouchEnd = () => {
state.isDragging = false;
document.removeEventListener('touchmove', handleTouchMove);
document.removeEventListener('touchend', handleTouchEnd);
};
const handleTouchStart = (event) => {
state.isDragging = true;
handleTouchMove(event);
document.addEventListener('touchmove', handleTouchMove);
document.addEventListener('touchend', handleTouchEnd);
};
return {
...toRefs(state),
handleMouseDown,
handleTouchStart,
};
},
};
</script>
<style>
.draggable {
width: 50px;
height: 50px;
position: absolute;
cursor: pointer;
background-color: #3498db;
border-radius: 50%;
color: white;
text-align: center;
line-height: 50px;
z-index: 1000;
user-select: none;
}
</style>
在这个示例中,.draggable
元素是悬浮球,它绑定了 mousedown
和 touchstart
事件处理函数,以便在用户开始拖动时进行响应。handleMouseMove
和 handleTouchMove
函数用于更新悬浮球的位置,handleMouseUp
、handleTouchEnd
和 handleMouseDown
函数用于处理拖动结束。这些函数在 setup
函数中返回,以便它们可以作为事件处理函数使用。