基于 Vue3 写一个 div的拖拽实现
时间: 2024-05-24 16:12:30 浏览: 99
基于Vue实现拖拽功能
html模板:
```html
<div class="drag-container">
<div class="drag-box" ref="box" :style="{top: top + 'px', left: left + 'px'}" @mousedown="dragStart"></div>
</div>
```
css样式:
```css
.drag-container {
position: relative;
width: 400px;
height: 400px;
background-color: #eee;
border: 1px solid #ccc;
}
.drag-box {
position: absolute;
width: 100px;
height: 100px;
background-color: #f00;
cursor: move;
}
```
Vue3代码实现:
```javascript
<script>
import { ref } from 'vue';
export default {
setup() {
const top = ref(100); // 初始top值
const left = ref(100); // 初始left值
let isDragging = false; // 是否正在拖拽
let startX = 0; // 鼠标按下时的初始x坐标
let startY = 0; // 鼠标按下时的初始y坐标
const dragStart = (e) => {
isDragging = true;
startX = e.clientX - left.value;
startY = e.clientY - top.value;
document.addEventListener('mousemove', dragMove);
document.addEventListener('mouseup', dragEnd);
};
const dragMove = (e) => {
if (isDragging) {
left.value = e.clientX - startX;
top.value = e.clientY - startY;
}
};
const dragEnd = () => {
isDragging = false;
document.removeEventListener('mousemove', dragMove);
document.removeEventListener('mouseup', dragEnd);
};
return {
top,
left,
dragStart,
};
},
};
</script>
```
效果:
![drag-demo](https://i.loli.net/2021/09/13/O34iKwzNl5cqJW8.png)
阅读全文