vue实现div拉伸
Vue 实现 Div 拉伸的方法
使用鼠标事件监听
通过监听 mousedown、mousemove 和 mouseup 事件实现 div 拉伸功能。在 Vue 的 methods 中定义相关事件处理函数,动态计算 div 的新尺寸。
<template>
<div
class="resizable"
:style="{ width: width + 'px', height: height + 'px' }"
@mousedown="startResize"
></div>
</template>
<script>
export default {
data() {
return {
width: 200,
height: 200,
isResizing: false
};
},
methods: {
startResize(e) {
this.isResizing = true;
document.addEventListener('mousemove', this.resize);
document.addEventListener('mouseup', this.stopResize);
},
resize(e) {
if (this.isResizing) {
this.width = e.clientX;
this.height = e.clientY;
}
},
stopResize() {
this.isResizing = false;
document.removeEventListener('mousemove', this.resize);
document.removeEventListener('mouseup', this.stopResize);
}
}
};
</script>
<style>
.resizable {
border: 1px solid #000;
position: relative;
cursor: se-resize;
}
</style>
使用 CSS resize 属性
利用 CSS 的 resize 属性可以快速实现 div 拉伸功能,但需要注意结合 overflow 属性使用。
<template>
<div class="resizable-css"></div>
</template>
<style>
.resizable-css {
width: 200px;
height: 200px;
border: 1px solid #000;
resize: both;
overflow: auto;
}
</style>
结合第三方库
使用如 vue-resizable 等第三方库可以更便捷地实现 div 拉伸功能,减少手动编写事件处理的代码量。

<template>
<vue-resizable :active="['r', 'b', 'rb']" :width="200" :height="200">
<div class="resizable-content"></div>
</vue-resizable>
</template>
<script>
import VueResizable from 'vue-resizable';
export default {
components: {
VueResizable
}
};
</script>
<style>
.resizable-content {
width: 100%;
height: 100%;
border: 1px solid #000;
}
</style>
注意事项
- 使用鼠标事件监听时,确保在组件销毁时移除事件监听,避免内存泄漏。
- CSS
resize属性在某些浏览器中可能不支持所有方向,需测试兼容性。 - 第三方库通常提供更多功能,如限制最小/最大尺寸、拖拽手柄等,适合复杂需求。






