五分钟学VUE会移动端拖拽事件

给标签绑定事件,组件标签需要.native修饰符

<Suspend
      class="suspend_box"
      @mousedown.native="down()"
      @touchstart.prevent.native="down()"
      @mousemove.native="move()"
      @touchmove.prevent.native="move()"
      @mouseup.native="end()"
      @touchend.prevent.native="end()"
      id="moveDiv"
    />

data中定义数据

data() {
    return {
      flags: false,
      position: { x: 0, y: 0 },
      nx: "",
      ny: "",
      dx: "",
      dy: "",
      xPum: "",
      yPum: ""
    };
  },

定义方法

down() {
      // console.log("手指按下");
      this.flags = true;
      let moveDiv = document.getElementById("moveDiv");
      var touch;
      // 判断屏幕上手指数量  如果多跟手指是个数组 否则是个对象
      if (event.touches) {
        touch = event.touches[0];
      } else {
        touch = event;
      }
      // 本地化手指每次按下的位置
      this.position.x = touch.clientX;
      this.position.y = touch.clientY;
      // 获保存取自身左外边框到定位父级的左内边框的距离
      this.dx = moveDiv.offsetLeft;
      this.dy = moveDiv.offsetTop;
    },
    move() {
      let moveDiv = document.getElementById("moveDiv");
      // 在手指按下时候flags已经为true
      if (this.flags) {
        var touch;
        // 70行
        if (event.touches) {
          touch = event.touches[0];
        } else {
          touch = event;
        }
        // clientX 当前手指位置距离当前body可视区域的x,y坐标
        // this.position.x  手指按下时元素位置
        //this.nx 元素每次相对于初始位置移动的坐标位置
        this.nx = touch.clientX - this.position.x;
        this.ny = touch.clientY - this.position.y;
        this.xPum = this.dx + this.nx;
        this.yPum = this.dy + this.ny;
        moveDiv.style.left = this.xPum + "px";
        moveDiv.style.top = this.yPum + "px";
      }
    },
    //鼠标释放时候的函数
    end() {
      this.flags = false;
    }

这时候因为没有阻止默认事件,拖拽会比较卡,而且会有一个报错
可以加一个**touch-action: none; **css属性,阻止所有的touch事件。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值