vue 拖动效果
时间: 2023-07-04 08:26:28 浏览: 142
Vue 拖动效果可以通过使用 Vue 指令来实现。下面是一个简单的实现示例:
1.在 Vue 组件中注册一个指令:
```javascript
directives: {
draggable: {
bind(el, binding) {
let startX, startY, initialMouseX, initialMouseY;
let draggable = el.querySelector('.draggable');
draggable.addEventListener('mousedown', (e) => {
startX = draggable.offsetLeft;
startY = draggable.offsetTop;
initialMouseX = e.clientX;
initialMouseY = e.clientY;
document.addEventListener('mousemove', mousemove);
document.addEventListener('mouseup', mouseup);
});
function mousemove(e) {
let dx = e.clientX - initialMouseX;
let dy = e.clientY - initialMouseY;
draggable.style.top = startY + dy + 'px';
draggable.style.left = startX + dx + 'px';
}
function mouseup() {
document.removeEventListener('mousemove', mousemove);
document.removeEventListener('mouseup', mouseup);
}
}
}
}
```
2.在组件模板中使用指令:
```html
<template>
<div class="container">
<div class="draggable" v-draggable>Drag me around</div>
</div>
</template>
```
这里我们使用 `v-draggable` 指令来绑定拖动事件,当用户按下鼠标左键并拖动时,`mousemove` 事件会触发并计算出鼠标移动的距离,然后通过给 `.draggable` 元素设置 `top` 和 `left` 样式来实现拖动效果。最后,在鼠标抬起时,我们需要移除监听器以防止出现意外情况。
阅读全文