vue实现拖拽改变尺寸
Vue 实现拖拽改变尺寸的方法
使用原生 HTML5 拖拽 API
通过监听 mousedown、mousemove 和 mouseup 事件实现拖拽调整尺寸。创建一个可拖拽的元素,计算鼠标移动距离并更新元素尺寸。
<template>
<div class="resizable" ref="resizable">
<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) {
const { width, height } = this.$refs.resizable.getBoundingClientRect();
this.$refs.resizable.style.width = `${width + e.movementX}px`;
this.$refs.resizable.style.height = `${height + e.movementY}px`;
},
stopResize() {
window.removeEventListener('mousemove', this.resize);
window.removeEventListener('mouseup', this.stopResize);
}
}
};
</script>
<style>
.resizable {
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-draggable-resizable 库,通过预定义的组件快速实现拖拽和调整尺寸功能。
npm install vue-draggable-resizable
<template>
<div>
<VueDraggableResizable :w="200" :h="200" @dragging="onDrag" @resizing="onResize" />
</div>
</template>
<script>
import VueDraggableResizable from 'vue-draggable-resizable';
export default {
components: {
VueDraggableResizable
},
methods: {
onDrag(x, y) {
console.log(x, y);
},
onResize(x, y, width, height) {
console.log(x, y, width, height);
}
}
};
</script>
使用 interact.js 实现高级拖拽调整
interact.js 是一个功能强大的拖拽库,支持复杂的拖拽和调整尺寸操作。
npm install interactjs
<template>
<div class="resizable" ref="resizable"></div>
</template>
<script>
import interact from 'interactjs';
export default {
mounted() {
interact(this.$refs.resizable)
.resizable({
edges: { right: true, bottom: true },
listeners: {
move: (event) => {
const { width, height } = event.rect;
event.target.style.width = `${width}px`;
event.target.style.height = `${height}px`;
}
}
});
}
};
</script>
<style>
.resizable {
width: 200px;
height: 200px;
border: 1px solid #000;
}
</style>
使用 CSS resize 属性
对于简单的调整尺寸需求,可以直接使用 CSS 的 resize 属性,但功能较为有限。
<template>
<div class="resizable"></div>
</template>
<style>
.resizable {
width: 200px;
height: 200px;
border: 1px solid #000;
resize: both;
overflow: auto;
}
</style>
以上方法可以根据具体需求选择,从简单的 CSS 实现到复杂的第三方库方案,灵活应对不同场景。







