vue实现easyui缩放
Vue 实现 EasyUI 缩放功能
在 Vue 中实现类似 EasyUI 的缩放功能,可以通过自定义指令或第三方库(如 vue-resizable)完成。以下是两种常见实现方式:
使用自定义指令实现缩放
通过 Vue 的自定义指令监听鼠标事件,动态调整元素宽高:

// 注册全局指令
Vue.directive('resizable', {
bind(el, binding) {
const minWidth = binding.value?.minWidth || 100;
const minHeight = binding.value?.minHeight || 100;
let startX, startY, startWidth, startHeight;
const handle = document.createElement('div');
handle.style.cssText = `
width: 10px;
height: 10px;
background: #666;
position: absolute;
right: 0;
bottom: 0;
cursor: se-resize;
`;
el.appendChild(handle);
handle.addEventListener('mousedown', (e) => {
e.preventDefault();
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(el).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(el).height, 10);
document.addEventListener('mousemove', resize);
document.addEventListener('mouseup', stopResize);
});
function resize(e) {
el.style.width = Math.max(minWidth, startWidth + e.clientX - startX) + 'px';
el.style.height = Math.max(minHeight, startHeight + e.clientY - startY) + 'px';
}
function stopResize() {
document.removeEventListener('mousemove', resize);
document.removeEventListener('mouseup', stopResize);
}
}
});
使用方式:
<template>
<div v-resizable="{ minWidth: 200, minHeight: 150 }" class="resizable-box"></div>
</template>
<style>
.resizable-box {
width: 300px;
height: 200px;
border: 1px solid #ccc;
position: relative;
}
</style>
使用 vue-resizable 库
安装库并快速实现缩放功能:

npm install vue-resizable --save
组件示例:
<template>
<vue-resizable :active="['r', 'b', 'rb']" :min-width="100" :min-height="80">
<div class="resizable-content">可缩放区域</div>
</vue-resizable>
</template>
<script>
import VueResizable from 'vue-resizable';
export default {
components: { VueResizable }
};
</script>
<style>
.resizable-content {
width: 200px;
height: 150px;
border: 1px dashed #42b983;
padding: 10px;
}
</style>
参数说明:
active: 控制缩放方向(r右,b下,rb右下角等)。min-width/min-height: 设置最小尺寸限制。
注意事项
- 性能优化:频繁的 DOM 操作可能影响性能,建议使用 CSS
transform或限制事件触发频率。 - 边界处理:添加对父容器边界的检测,避免元素被拖出可视区域。
- 移动端适配:如需支持触摸事件,需额外监听
touchstart/touchmove事件。
通过以上方法,可以灵活实现类似 EasyUI 的缩放交互效果。






