vue拖拽改变页面宽度

448 阅读1分钟

一、封装组件ResizeBox.vue

<template>
  <div ref="resize" class="resize">
    <div ref="resizeHandle" class="handle-resize" />
    <slot />
  </div>
</template>
<script>
export default {
  name: 'ResizeBox',
  props: {
    resizeConf: {
      type: Object,
      default: () => ({
        width: 400, // 初始宽度
        widthRange: [400, 800] // 宽度范围
      })
    }
  },
  mounted() {
    this.dragControllerDiv()
  },
  methods: {
    dragControllerDiv() {
      this.$refs.resize.style.width = `${this.resizeConf.width}px` // 默认宽度
      // 鼠标按下事件
      this.$refs.resizeHandle.onmousedown = (e) => {
        const resizeWidth = this.$refs.resize.offsetWidth
        const startX = e.clientX // 水平坐标
        console.log('e.clientX', e.clientX, this.$refs.resize.offsetWidth)
        // 鼠标拖动事件
        document.onmousemove = (ev) => {
          const moveX = ev.clientX
          const moveLen = resizeWidth + (moveX - startX)
          console.log('ev.clientX', ev.clientX, this.$refs.resize.offsetWidth)
          if (
            this.resizeConf.widthRange[0] <= moveLen &&
            this.resizeConf.widthRange[1] >= moveLen
          ) {
            this.$refs.resize.style.width = `${moveLen}px`
          }
        }
        // 鼠标松开事件
        document.onmouseup = () => {
          document.onmousemove = null
          document.onmouseup = null
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.resize {
  height: 800px;
  background: #fbfbfb;
  position: relative;
  word-wrap: break-word;

  .handle-resize {
    cursor: col-resize;
    position: absolute;
    top: 0;
    right: 0;
    width: 6px;
    height: 800px;
    // border-left: 2px solid #c5c5c5;
    // border-right: 2px solid #c5c5c5;
  }
}
</style>

二、组件使用

<template>
  <div class="container sa-flex">
    <ResizeBox :resize-conf="resizeConf"> 嗨,左边 </ResizeBox>
    <div class="right sa-flex-1">嗨,右边</div>
  </div>
</template>
<script>
import ResizeBox from './ResizeBox.vue'

export default {
  components: {
    ResizeBox
  },
  data() {
    return {
      resizeConf: {
        width: 400, // 初始宽度
        widthRange: [400, 800] // 宽度范围
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.sa-flex {
  display: flex;
  flex-wrap: no-wrap;
}
.sa-flex-1 {
  flex: 1;
}
.container {
  height: 800px;
  background: #eee;
}
</style>

三、效果图

image.png

image.png

参考文章:blog.csdn.net/Guoyu1_/art…