vue实现拖拽边框改变元素宽度
时间: 2023-09-12 18:08:35 浏览: 56
Vue可以通过绑定mousedown、mousemove、mouseup事件来实现拖拽边框改变元素宽度。具体步骤如下:
1. 绑定mousedown事件,在事件处理函数中记录鼠标点击的初始位置和被拖拽元素的初始宽度。
2. 绑定mousemove事件,在事件处理函数中计算鼠标的相对移动距离,并根据鼠标移动距离更新被拖拽元素的宽度。
3. 绑定mouseup事件,在事件处理函数中取消mousemove和mouseup事件的绑定。
下面是示例代码:
```
<template>
<div class="drag-wrapper">
<div class="drag-target" :style="{ width: targetWidth + 'px' }">
Drag Me
</div>
<div class="drag-handle" @mousedown="handleDown"></div>
</div>
</template>
<script>
export default {
data () {
return {
isDragging: false,
startX: 0,
startWidth: 0,
targetWidth: 200
}
},
methods: {
handleDown (e) {
this.isDragging = true
this.startX = e.clientX
this.startWidth = this.targetWidth
document.addEventListener('mousemove', this.handleMove)
document.addEventListener('mouseup', this.handleUp)
},
handleMove (e) {
if (!this.isDragging) return
const deltaX = e.clientX - this.startX
this.targetWidth = this.startWidth + deltaX
},
handleUp () {
this.isDragging = false
document.removeEventListener('mousemove', this.handleMove)
document.removeEventListener('mouseup', this.handleUp)
}
}
}
</script>
<style scoped>
.drag-wrapper {
position: relative;
height: 100px;
padding: 10px;
background-color: #ddd;
}
.drag-target {
height: 100%;
background-color: #fff;
text-align: center;
line-height: 80px;
font-size: 20px;
border: 1px solid #333;
}
.drag-handle {
position: absolute;
top: 0;
right: -5px;
bottom: 0;
width: 10px;
background-color: #333;
cursor: ew-resize;
}
</style>
```