vue实现拖动宽度
Vue 实现拖动调整宽度
在 Vue 中实现拖动调整宽度可以通过监听鼠标事件和使用 CSS 样式来实现。以下是具体实现方法:
使用鼠标事件监听
创建一个可拖动的分隔条,通过监听 mousedown、mousemove 和 mouseup 事件来调整宽度。
<template>
<div class="container">
<div class="left-panel" :style="{ width: leftWidth + 'px' }">左侧面板</div>
<div class="divider" @mousedown="startDrag"></div>
<div class="right-panel">右侧面板</div>
</div>
</template>
<script>
export default {
data() {
return {
leftWidth: 200,
isDragging: false
};
},
methods: {
startDrag(e) {
this.isDragging = true;
document.addEventListener('mousemove', this.onDrag);
document.addEventListener('mouseup', this.stopDrag);
},
onDrag(e) {
if (this.isDragging) {
this.leftWidth = e.clientX;
}
},
stopDrag() {
this.isDragging = false;
document.removeEventListener('mousemove', this.onDrag);
document.removeEventListener('mouseup', this.stopDrag);
}
}
};
</script>
<style>
.container {
display: flex;
height: 100vh;
}
.left-panel {
background: #f0f0f0;
}
.divider {
width: 5px;
background: #ccc;
cursor: col-resize;
}
.right-panel {
flex: 1;
background: #e0e0e0;
}
</style>
使用第三方库
如果需要更复杂的功能,可以使用第三方库如 vue-resizable 或 interact.js。
使用 interact.js 实现
安装 interact.js:
npm install interactjs
在 Vue 组件中使用:
<template>
<div class="container">
<div ref="resizable" class="resizable">可拖动调整宽度的元素</div>
</div>
</template>
<script>
import interact from 'interactjs';
export default {
mounted() {
interact(this.$refs.resizable)
.resizable({
edges: { right: true },
listeners: {
move: (event) => {
let { width } = event.rect;
event.target.style.width = `${width}px`;
}
}
});
}
};
</script>
<style>
.resizable {
width: 200px;
height: 100px;
background: #f0f0f0;
border: 1px solid #ccc;
}
</style>
使用 Vue 指令封装
可以封装一个自定义指令来简化拖动逻辑。
Vue.directive('resize', {
bind(el, binding) {
const direction = binding.value || 'horizontal';
const handler = document.createElement('div');
handler.className = 'resize-handler';
el.appendChild(handler);
el.style.position = 'relative';
handler.addEventListener('mousedown', (e) => {
document.addEventListener('mousemove', resize);
document.addEventListener('mouseup', stopResize);
});
function resize(e) {
if (direction === 'horizontal') {
el.style.width = `${e.clientX - el.getBoundingClientRect().left}px`;
}
}
function stopResize() {
document.removeEventListener('mousemove', resize);
}
}
});
在模板中使用:
<div v-resize="'horizontal'" style="width: 200px; height: 100px; background: #f0f0f0;"></div>
注意事项
- 拖动过程中可能需要限制最小和最大宽度,可以在事件处理函数中添加逻辑。
- 在移动端需要额外处理触摸事件(
touchstart、touchmove、touchend)。 - 使用第三方库时,注意在组件销毁时清理事件监听,避免内存泄漏。







