拖拽移动的vue3组件
时间: 2023-09-30 15:02:55 浏览: 78
基于Vue实现拖拽功能
以下是一个基于Vue3编写的拖拽移动组件:
```
<template>
<div class="drag" :style="{ top: position.y + 'px', left: position.x + 'px' }" @mousedown="startDrag">
<slot></slot>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'Draggable',
props: {
x: {
type: Number,
default: 0
},
y: {
type: Number,
default: 0
}
},
setup(props) {
const position = ref({ x: props.x, y: props.y });
const dragging = ref(false);
const delta = ref({ x: 0, y: 0 });
const startDrag = (event) => {
event.preventDefault();
dragging.value = true;
delta.value.x = event.clientX - position.value.x;
delta.value.y = event.clientY - position.value.y;
window.addEventListener('mousemove', moveDrag);
window.addEventListener('mouseup', stopDrag);
};
const moveDrag = (event) => {
if (dragging.value) {
position.value.x = event.clientX - delta.value.x;
position.value.y = event.clientY - delta.value.y;
}
};
const stopDrag = () => {
dragging.value = false;
window.removeEventListener('mousemove', moveDrag);
window.removeEventListener('mouseup', stopDrag);
};
return {
position,
startDrag
};
}
};
</script>
<style scoped>
.drag {
position: absolute;
cursor: move;
}
</style>
```
使用示例:
```
<template>
<div class="container">
<draggable x="100" y="100">
<div class="box">Drag me!</div>
</draggable>
</div>
</template>
<script>
import Draggable from './Draggable.vue';
export default {
components: {
Draggable
}
};
</script>
<style scoped>
.container {
position: relative;
height: 500px;
background-color: #eee;
}
.box {
width: 100px;
height: 100px;
background-color: #f00;
color: #fff;
text-align: center;
line-height: 100px;
}
</style>
```
这个组件会在页面上显示一个红色的正方形,你可以通过鼠标拖拽它在页面上移动。你也可以通过指定`x`和`y`属性来设置初始位置。
阅读全文