拖拽改变左侧侧边栏的宽度,按照下面的写法,必须得缓慢的一点点拖拽才能改变大小,很难用而且左右拖拽不灵活。
原写法
<div class="rank" @mousedown="mousedownEvent" @mouseleave="mouseleave" @mousemove="mouseMove">
mouseMove(e) {
if (!this.isMoving) {
return;
}
const offsetx = e.clientX
if ((this.move.initOffsetx > offsetx && this.asideWidth >= 500) || this.move.initOffsetx < offsetx && this.asideWidth <= 750) {
this.asideWidth = this.asideWidth + (offsetx - this.move.initOffsetx)
this.move.initOffsetx = offsetx
return;
}
},
mousedownEvent(e) {
this.isMoving = true;
this.move.initOffsetx = e.clientX
},
mouseleave(e) {
this.isMoving = false;
},
找了资料发现,当鼠标离开绑定了mouse系列事件的组件之后,会终止拖拽事件。所以需要将mousemove绑定在一个足够大的父容器上才能继续生效,哪里还有比window更大的呢。
中间我还尝试了用document.mousemove,效果没啥差别,不好用。
最终好用方案
controlAsideWidth(e) {
const offsetx = e.clientX
if ((this.move.initOffsetx > offsetx && this.asideWidth >= 500) || this.move.initOffsetx < offsetx && this.asideWidth <= 750) {
this.asideWidth = this.asideWidth + (offsetx - this.move.initOffsetx)
this.move.initOffsetx = offsetx
return;
}
},
mousedownMove(e) {
this.move.initOffsetx = e.clientX
// 添加mousemove到window这个大容器上
window.addEventListener("mousemove", this.controlAsideWidth)
},
// 离开页面时再销毁即可
beforeDestroy() {
window.removeEventListener('mousemove', this.controlAsideWidth)
}