用vue封装一个页面可以拖动按钮
这段代码定义了一个DraggableButton组件,该组件可用于在页面上创建可拖动按钮。该组件接受两个道具:x和y,它们指定按钮在页面上的初始位置,并在按钮被拖动时发出一个拖动事件。
组件使用data函数来管理按钮的拖动状态和位置。handleMouseDown和handleTouchStart方法处理拖动操作的开始,handleMouseMove和handleTouchMove方法处理拖动操作期间按钮的移动。handleMouseUp和handleTouchEnd方法处理拖动操作的结束。
<template>
<div
ref="button"
:style="{
position: 'absolute',
top: `${y}px`,
left: `${x}px`,
cursor: 'grab',
cursor: '-webkit-grab',
zIndex: 9999,
}"
@mousedown="handleMouseDown"
@touchstart="handleTouchStart"
>
Drag me!
</div>
</template>
<script>
export default {
props: {
x: {
type: Number,
default: 0,
},
y: {
type: Number,
default: 0,
},
},
data() {
return {
isDragging: false,
offsetX: 0,
offsetY: 0,
};
},
methods: {
handleMouseDown(event) {
this.isDragging = true;
this.offsetX = event.clientX - this.x;
this.offsetY = event.clientY - this.y;
document.addEventListener('mousemove', this.handleMouseMove);
document.addEventListener('mouseup', this.handleMouseUp);
},
handleMouseMove(event) {
if (this.isDragging) {
const newX = event.clientX - this.offsetX;
const newY = event.clientY - this.offsetY;
this.$emit('drag', newX, newY);
}
},
handleMouseUp() {
this.isDragging = false;
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
},
handleTouchStart(event) {
this.isDragging = true;
this.offsetX = event.touches[0].clientX - this.x;
this.offsetY = event.touches[0].clientY - this.y;
document.addEventListener('touchmove', this.handleTouchMove);
document.addEventListener('touchend', this.handleTouchEnd);
},
handleTouchMove(event) {
if (this.isDragging) {
const newX = event.touches[0].clientX - this.offsetX;
const newY = event.touches[0].clientY - this.offsetY;
this.$emit('drag', newX, newY);
}
},
handleTouchEnd() {
this.isDragging = false;
document.removeEventListener('touchmove', this.handleTouchMove);
document.removeEventListener('touchend', this.handleTouchEnd);
},
},
mounted() {
this.$refs.button.addEventListener('mousedown', this.handleMouseDown);
this.$refs.button.addEventListener('touchstart', this.handleTouchStart);
},
beforeDestroy() {
this.$refs.button.removeEventListener('mousedown', this.handleMouseDown);
this.$refs.button.removeEventListener('touchstart', this.handleTouchStart);
},
};
</script>
要使用这个组件,你可以将它导入到你的页面中,并像这样渲染它:
<template>
<div>
<DraggableButton :x="buttonPosition.x" :y="buttonPosition.y" @drag="handleDrag" />
</div>
</template