项目需求:页面左右布局,需要拖拽分割线,实现宽度自动适应。
解决方案:在mounted生命周期,监听分割线DOM的onmousedown事件,在拖拽过程中动态计算,然后赋值改变左右DOM元素的宽度。
<template>
<div class="wrap">
<div class="lf" ref="letfDom" :style="{width: curWidth}">
<router-link to="/moreClick">moreClick</router-link>
<div class="touch-div" ref="moveDom"> </div>
</div>
<div class="rt" :style="{width: curRightWidth}">
<router-view />
</div>
</div>
</template>
export default {
name: "App",
data() {
return {
leftDom: null,
clientStartX: 0,
curWidth: '280px',
curRightWidth: 0,
};
},
mounted() {
const wrap = this.$refs.wrap;
const wrapWidth = wrap.clientWidth
this.leftDom = this.$refs.leftDom;
const leftWidth = this.leftDom.clientWidth
let moveDom = this.$refs.moveDom;
this.curRightWidth = wrapWidth - leftWidth + "px"
moveDom.onmousedown = e => {
this.clientStartX = e.clientX;
e.preventDefault();
document.onmousemove = e => {
this.moveHandle(e.clientX, this.leftDom);
};
document.onmouseup = e => {
document.onmouseup = null;
document.onmousemove = null;
};
};
},
methods: {
moveHandle(nowClientX, leftDom) {
const wrap = this.$refs.wrap;
const wrapWidth = wrap.clientWidth
// 左边
let computedX = nowClientX - this.clientStartX;
let leftBoxWidth = parseInt(leftDom.style.width);
let changeWidth = leftBoxWidth + computedX;
if (changeWidth < 150) {
changeWidth = 150;
}
if (changeWidth > 400) {
changeWidth = 400;
}
this.curWidth = changeWidth + "px";
// 右边
this.curRightWidth = wrapWidth - changeWidth + "px"
// 刷新起点
this.clientStartX = nowClientX
},
}
}
<style lang="scss" scoped>
.wrap{
display: flex;
height: 100%;
.lf{
height: 100%;
display: flex;
align-items: stretch;
.treeWrap{
width: calc(100% - 12px);
}
.touch-div{
height: 100%;
width: 1px;
cursor: col-resize;
margin-left: 10px;
border-right: 1px solid #DCDFE6;
}
}
.rf{
padding-left: 10px;
}
}
</style>