vue2 实现左右拖拽调整宽度的功能
一、模板结构调整
<template>
<div class="mobile-list-container">
<!-- 左侧列表容器 -->
<div class="aside" :style="{ width: leftWidth + 'px' }" @scroll="handleScroll">
<!-- 原有列表内容保持不变 -->
</div>
<!-- 拖拽条 -->
<div
class="resize-handle"
@mousedown="startResize"
@touchstart.passive="startResize"
></div>
<!-- 右侧内容区域 -->
<div class="itemContent" :style="{ width: `calc(100% - ${leftWidth}px)` }">
<!-- 原有内容保持不变 -->
</div>
</div>
</template>
二、脚本部分新增
<script>
export default {
data() {
return {
leftWidth: 330,
isResizing: false
}
},
methods: {
startResize(e) {
this.isResizing = true
window.addEventListener('mousemove', this.handleResize)
window.addEventListener('touchmove', this.handleResize)
window.addEventListener('mouseup', this.stopResize)
window.addEventListener('touchend', this.stopResize)
},
handleResize(e) {
if (!this.isResizing) return
const containerRect = this.$el.getBoundingClientRect()
const clientX = e.clientX || e.touches[0].clientX
const newWidth = clientX - containerRect.left
this.leftWidth = Math.max(200, Math.min(600, newWidth))
},
stopResize() {
this.isResizing = false
window.removeEventListener('mousemove', this.handleResize)
window.removeEventListener('touchmove', this.handleResize)
window.removeEventListener('mouseup', this.stopResize)
window.removeEventListener('touchend', this.stopResize)
}
}
}
</script>
三、新增CSS样式
.resize-handle {
position: absolute;
top: 0;
bottom: 0;
width: 8px;
background: #EBEBEB;
cursor: col-resize;
z-index: 100;
transition: background 0.2s;
&:hover,
&:active {
background: #409EFF;
}
}
.mobile-list-container {
position: relative;
display: flex;
height: 100vh;
}