vue拖拽滑动分割面板

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue拖拽滑动分割面板

推开世界的门   2022-05-28 我要评论

需求背景

左边是列表,右边是详情。 想更大范围的查看详情,所以要拖拽滑块,进行面板的分割

整体思路

  • 在布局上,采用flex布局,单位采用百分比。设置flex:1,让其自动伸缩
  • 滑动滑块,计算滑块在滑动过程中,占整个页面的百分比
  • 将百分比,通过动态样式赋值给列表页的宽度
  • 同时改变滑块的位置(也是百分比形式)
  • 其次就是在vue里对鼠标事件的使用

代码实现

在template里 写事件

@mousedown.prevent="mousedown"

在methods里写方法

/**
     * 按下鼠标
     */
      mousedown() {
        document.addEventListener('mousemove', this.handleMouseMove, false);
        document.addEventListener('mouseup', this.handleMouseUp, false);
    },
    /**
     * 按下滑动器,移动鼠标
     */
    handleMouseMove(e) {
      /**
       * 计算容器总宽度
       * 计算滑块到左边的距离
       * 计算偏移百分比: (滑块距离左边的距离 / 页面宽度) * 100
       * 传递移动百分比和距左边的距离
       */
      const clientRect = this.$refs.mainContent.getBoundingClientRect();
      const offset = e.pageX;
      const panelPercent = (offset / clientRect.width) * 100;
      this.panelPercent = panelPercent;
      this.mainContentWidth = offset;
      this.$refs.imgMove.style.left = panelPercent + '%';
      console.log('拖动中', this.panelPercent);
    },
    /**
     * 松开滑动器
     */
    handleMouseUp () {
      document.removeEventListener('mousemove', this.handleMouseMove, false);
    },

对边界处理

if (this.panelPercent < this.min) {
        this.panelPercent = this.min
      }
      if (this.panelPercent > this.max) {
        this.panelPercent = this.max
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们