vue 拖拽改变宽度

<template>
  <div class="x-handle" unselectable="on" onselectstart="return false" @mousedown="mouseDown"></div>
</template>

<script>
export default {
  name: 'XDragHandle',
  data() {
    return {
      lastX: '',
    }
  },
  created() {
    document.addEventListener('mouseup', this.mouseUp)
  },
  destroyed() {
    document.removeEventListener('mouseup', this.mouseUp)
  },
  methods: {
    mouseUp() {
      this.lastX = ''
      document.removeEventListener('mousemove', this.mouseMove)
    },
    mouseDown(event) {
      document.addEventListener('mousemove', this.mouseMove)
      this.lastX = event.screenX
    },
    mouseMove(event) {
      console.log('move')
      this.$emit('widthChange', this.lastX - event.screenX)
      this.lastX = event.screenX
    },
  },
}
</script>

<style lang="scss" scoped>
.x-handle {
  width: 2px;
  cursor: w-resize;
  z-index: 10;
  background-color: #f1f4f9;
}
</style>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue可以通过绑定mousedown、mousemove、mouseup事件来实现拖拽边框改变元素宽度。具体步骤如下: 1. 绑定mousedown事件,在事件处理函数中记录鼠标点击的初始位置和被拖拽元素的初始宽度。 2. 绑定mousemove事件,在事件处理函数中计算鼠标的相对移动距离,并根据鼠标移动距离更新被拖拽元素的宽度。 3. 绑定mouseup事件,在事件处理函数中取消mousemove和mouseup事件的绑定。 下面是示例代码: ``` <template> <div class="drag-wrapper"> <div class="drag-target" :style="{ width: targetWidth + 'px' }"> Drag Me </div> <div class="drag-handle" @mousedown="handleDown"></div> </div> </template> <script> export default { data () { return { isDragging: false, startX: 0, startWidth: 0, targetWidth: 200 } }, methods: { handleDown (e) { this.isDragging = true this.startX = e.clientX this.startWidth = this.targetWidth document.addEventListener('mousemove', this.handleMove) document.addEventListener('mouseup', this.handleUp) }, handleMove (e) { if (!this.isDragging) return const deltaX = e.clientX - this.startX this.targetWidth = this.startWidth + deltaX }, handleUp () { this.isDragging = false document.removeEventListener('mousemove', this.handleMove) document.removeEventListener('mouseup', this.handleUp) } } } </script> <style scoped> .drag-wrapper { position: relative; height: 100px; padding: 10px; background-color: #ddd; } .drag-target { height: 100%; background-color: #fff; text-align: center; line-height: 80px; font-size: 20px; border: 1px solid #333; } .drag-handle { position: absolute; top: 0; right: -5px; bottom: 0; width: 10px; background-color: #333; cursor: ew-resize; } </style> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值