侧滑栏组件(vue组件)实现自由拖动调节宽度大小

2,255 阅读1分钟

需求

  1. 侧滑栏组件的width属性可以定义侧滑栏的宽度,但用户如果觉得这个宽度大小不合适的时候,没法改变。
  2. 所以多增加一个属性isDrag,用于设置侧滑栏宽度是否可以自由拖动改变,方便用户根据自己的需要来改变侧滑栏的宽度。

实现方法

1. 新增isDrag属性,控制侧滑栏是否可拖动,默认为false

 props: {
            content: String,
            isShowFullScreenButton: { type: Boolean, default: false },
            width: { type: String, default: '800px' },
            isDrag:{type: Boolean, default: false},
        },

2. 模板中增加分割线,用于控制拖动

<template lang="pug">
    .slide.zFadeInRight(ref="slide", v-show="isShow", :style="{ width: isFullScreen? '100%' : offWidth }")
        .split(v-if="isDrag", @mousedown="handleMousedown")
        .slideBd(ref="slideBody", tabindex="-1", @keyup.esc="hide")
            slot {{content}}
</template>

.split
        position absolute
        top 0
        left 0
        width 6px
        height 100%
        background-color transparent
        z-index: 10;
        user-select: none;
        cursor: col-resize;

3.分割线上添加mousedown事件,绑定handleMousedown方法

handleMousedown (event) {
    document.addEventListener('mousemove', this.handleMousemove);
    document.addEventListener('mouseup', this.handleMouseup);
    this.canMove = true
},
handleMousemove (event) {
    if (!this.canMove) return;
        let bodyWidth = document.body.getBoundingClientRect().width;
        let offWidth = bodyWidth - event.pageX  + 6/2;
        offWidth = offWidth >= bodyWidth ? bodyWidth: offWidth;
        offWidth = offWidth <= 300 ? 300 : offWidth;
        this.offWidth = offWidth + 'px';
},
handleMouseup () {
    this.canMove = false;
}
  1. handleMousedown方法中,document对象上添加mousemove和mouseup事件,绑定对应的handleMousemove和handleMouseup方法
  2. handleMousemove方法中获取body对象的宽度和鼠标距离页面左边的距离,计算出侧滑栏的宽度。
  3. handleMouseup方法,用于释放鼠标后,canMove设为false,这样鼠标再移动的时候侧滑栏宽度不会再变化。

4. beforeDestroy方法中,document对象移除mousemove和mouseup事件,避免内存泄漏

beforeDestroy() {
    document.removeEventListener('mousemove', this.handleMousemove);
    document.removeEventListener('mousemove', this.handleMouseup);
},