vue拖拉拽案例
时间: 2023-06-21 10:13:20 浏览: 105
以下是一个基于Vue的简单拖拽案例:
```html
<template>
<div class="container">
<div class="box" :style="{top: boxPosY + 'px', left: boxPosX + 'px'}" @mousedown="dragStart" @mouseup="dragEnd">
Drag me!
</div>
</div>
</template>
<script>
export default {
data() {
return {
isDragging: false,
startPosX: 0,
startPosY: 0,
boxPosX: 0,
boxPosY: 0
};
},
methods: {
dragStart(event) {
this.isDragging = true;
this.startPosX = event.clientX;
this.startPosY = event.clientY;
},
dragEnd() {
this.isDragging = false;
}
},
mounted() {
const container = document.querySelector('.container');
container.addEventListener('mousemove', event => {
if (this.isDragging) {
const deltaX = event.clientX - this.startPosX;
const deltaY = event.clientY - this.startPosY;
this.boxPosX += deltaX;
this.boxPosY += deltaY;
this.startPosX = event.clientX;
this.startPosY = event.clientY;
}
});
}
};
</script>
<style>
.container {
width: 100%;
height: 100vh;
background-color: #eee;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 100px;
height: 100px;
background-color: #f00;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
position: absolute;
cursor: move;
}
</style>
```
上面的代码实现了一个简单的拖拽效果,当鼠标按下时,box会跟随鼠标移动,当鼠标松开时,box停止移动。代码中用到了data、methods和mounted等Vue基础用法,以及事件监听和DOM操作等知识点。
阅读全文