div可拖拽宽度

<template>
 <div class="x-handle" @mousedown="mouseDown"></div>
</template>

<script>
export default {
 name: 'HandleEvent',
 data() {
  return {
   lastX: '',
  }
 },
 methods: {
  // 在 类move_div 上按下鼠标左键时,监听鼠标移动
  mouseDown(event) {
   document.addEventListener('mousemove', this.mouseMove)
  },
  // 移动到的位置
  mouseMove(event) {
   let width = event.clientX
   // 这里的减去的值是左侧伸缩栏的宽度,根据伸缩状态减去200 或 64
   if (JSON.parse(localStorage.getItem('isCollapse'))) {
    this.lastX = width - 64
   } else {
    this.lastX = width - 200
   }
   this.$emit('widthChange', this.lastX)
  },
  mouseUp() {
   // 左键抬起时,移除监听事件
   document.removeEventListener('mousemove', this.mouseMove)
  },
 },
 created() {
  document.addEventListener('mouseup', this.mouseUp)
 },
 destroyed() {
  document.removeEventListener('mouseup', this.mouseUp)
 },
}
</script>
<style lang="scss">
.x-handle {
 width: 2px;
 z-index: 10;
 background: #ccc;
 cursor: ew-resize;
}
</style>

在组件中调用:

1、import HandleEvent from '../../component-tool/HandleEvent.vue'

2、 components: {
  'handle-event': HandleEvent,
 },

3、<handle-event class="xhandle" @widthChange="widthChange" />

4、  methods中:
  widthChange(width) {
   this.tree_width = width // 自定义元素
   let table_box = document.getElementById('table_box') // 自定义
   table_box.style.left = this.tree_width + 3 + 'px'  // 自定义
  },

 

posted @ 2022-11-02 11:24  yw3692582  阅读(66)  评论(0编辑  收藏  举报