在Vue中,可以通过绑定事件来实现页面上盒子的移动。常用的事件有:
- @mousemove:当鼠标指针在元素内部移动时触发。
- @mousedown:当鼠标按钮被按下时触发。
- @mouseup:当鼠标按钮被松开时触发。
- 相关代码html代码
-
<div id="app"> <div id="box" @mousedown="startDrag" @mousemove="dragging" @mouseup="stopDrag" :style="{ top: top + 'px', left: left + 'px' }"> </div> </div>
css代码
-
#box { width: 100px; height: 100px; background-color: red; position: absolute; }
js相关代码
-
new Vue({ data: { isDragging: false, lastX: 0, lastY: 0, left: 50, top: 50 }, methods: { startDrag(e) { this.isDragging = true; this.lastX = e.clientX; this.lastY = e.clientY; }, dragging(e) { if (this.isDragging) { let deltaX = e.clientX - this.lastX; let deltaY = e.clientY - this.lastY; this.left += deltaX; this.top += deltaY; this.lastX = e.clientX; this.lastY = e.clientY; } }, stopDrag() { this.isDragging = false; } } })