vue实现拉伸
Vue 实现拉伸功能
在 Vue 中实现拉伸功能通常涉及元素的拖拽调整大小。以下是几种常见的实现方法:
使用 CSS 和事件监听
通过 CSS 设置可拉伸区域,结合 Vue 的事件监听实现拉伸效果。

<template>
<div class="resizable-box" ref="box">
<div class="resizer" @mousedown="startResize"></div>
</div>
</template>
<script>
export default {
methods: {
startResize(e) {
window.addEventListener('mousemove', this.resize);
window.addEventListener('mouseup', this.stopResize);
},
resize(e) {
this.$refs.box.style.width = `${e.clientX - this.$refs.box.getBoundingClientRect().left}px`;
this.$refs.box.style.height = `${e.clientY - this.$refs.box.getBoundingClientRect().top}px`;
},
stopResize() {
window.removeEventListener('mousemove', this.resize);
window.removeEventListener('mouseup', this.stopResize);
}
}
}
</script>
<style>
.resizable-box {
position: relative;
width: 200px;
height: 200px;
border: 1px solid #000;
}
.resizer {
position: absolute;
right: 0;
bottom: 0;
width: 10px;
height: 10px;
background: #000;
cursor: se-resize;
}
</style>
使用第三方库
Vue-Draggable-Resizable 是一个专门用于实现拖拽和拉伸的 Vue 组件。
安装:

npm install vue-draggable-resizable
使用:
<template>
<VueDraggableResizable :w="200" :h="200" :x="0" :y="0">
<p>可拉伸和拖拽的元素</p>
</VueDraggableResizable>
</template>
<script>
import VueDraggableResizable from 'vue-draggable-resizable';
export default {
components: {
VueDraggableResizable
}
}
</script>
使用 SVG 实现拉伸
对于 SVG 元素,可以通过控制 viewBox 或直接操作 SVG 元素的属性来实现拉伸。
<template>
<svg ref="svg" @mousedown="startDrag" @mousemove="drag" @mouseup="endDrag">
<rect x="10" y="10" width="100" height="100" fill="blue" />
</svg>
</template>
<script>
export default {
data() {
return {
isDragging: false
}
},
methods: {
startDrag() {
this.isDragging = true;
},
drag(e) {
if (this.isDragging) {
const svg = this.$refs.svg;
const rect = svg.querySelector('rect');
rect.setAttribute('width', e.clientX - svg.getBoundingClientRect().left);
rect.setAttribute('height', e.clientY - svg.getBoundingClientRect().top);
}
},
endDrag() {
this.isDragging = false;
}
}
}
</script>
注意事项
- 性能优化:频繁的 DOM 操作会影响性能,建议使用 requestAnimationFrame 进行优化。
- 边界检查:实现拉伸功能时,需要检查边界条件,防止元素拉伸到不可见区域。
- 移动端适配:如果需要支持移动端,需要添加 touch 事件处理。
以上方法可以根据具体需求选择使用,纯 CSS 和 JavaScript 实现适合简单场景,第三方库则提供了更完善的功能和更好的兼容性。






