vue拖拽组件超好用!!!

vue拖拽组件

在vue实现拖拽,经常使用到,所以自己封装了成了一个组件
效果展示
在这里插入图片描述

组件代码

<template>
 <div class="dragBtn" @touchstart="move" @click="clickMove" ref="oDiv" :style="{'width': width + 'px', 'height': height + 'px'}">
   <slot>

   </slot>
 </div>
</template>

<script>
export default {
  // distance 数组 ['上', '右', '下', '左']
  props: {
    distance: {
      require: false,
      type: Array
    },
    width: {
      require: false,
      type: Number,
      default: 50
    },
    height: {
      require: false,
      type: Number,
      default: 50
    }
  },
  data () {
    return {
      defalutDistance: []
    }
  },
  created () {
    if (!this.distance) {
      this.defalutDistance = [0, window.screen.availWidth - this.width, window.screen.availHeight - this.height,0 ]
      console.log(this.defalutDistance)
    }
  },
  methods: {
    move (e) {
      e.stopPropagation()
      const oDiv = this.$refs['oDiv']
      const disX = e.touches[0].clientX - oDiv.offsetLeft
      const disY = e.touches[0].clientY - oDiv.offsetTop
      document.addEventListener('touchmove', myFunction, { passive: false })
      let distance = this.defalutDistance
      if (this.distance) {
        distance = this.distance
      }
      function myFunction(e) {
          e.preventDefault()
          let left = e.touches[0].clientX - disX
          let top = e.touches[0].clientY - disY
          if (left <= distance[3]) {
            left = distance[3]
          }
          if (left >= distance[1]) {
            left = distance[1]
          }
          if (top <= distance[0]) {
            top = distance[0]
          }
          if (top >= distance[2]) {
            top = distance[2]
          }
          oDiv.style.left = left + 'px'
          oDiv.style.top = top + 'px'
      }
      document.addEventListener('touchend', () => {
        document.removeEventListener('touchmove', myFunction, { passive: false })
        document.removeEventListener('touchend', myFunction, { passive: false })
      })
    },
    clickMove (e) {
      e.stopPropagation()
      this.$emit('clickMove', e)
    }
  }
}
</script>

<style scoped>
.dragBtn {
  /* width: 50px;
  height: 50px; */
  /* border-radius: 50%; */
  /* background-color: violet; */
  position: fixed;
  z-index: 1000;
  bottom: 40px;
  right: 40px;
  /* background-image: url('../assets/image/change.png'); */
  /* background-size: cover; */
  /* border: 1px solid red; */
  z-index: 99;
}
</style>

使用组件

<z-drag @clickMove="showPopup = true" :width="50" :height="50">
  <van-icon name="add-o" class="addIcon" />
</z-drag>

欢迎使用!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值