Vue 拖动事件处理程序未触发

问题描述 投票:0回答:1

我正在尝试按照这篇文章进行操作,通过拖动项目将其移动到屏幕上的任何位置:https://www.kirupa.com/html5/drag.htm问题是这篇文章是常规的JavaScript 和我使用的是 Vue,因此事件处理程序的处理方式略有不同。由于某种原因,@dragStart 和 @drag 根本不会触发,但 @dragEnd 会在用户停止拖动项目时触发。

我仅使用这个div

<div class="pip" draggable="true" @dragStart="dragStart" @drag="drag" @dragend="dragEnd">

脚本标签

data() {
    return {
      active: false,
      currentX: null,
      currentY: null,
      initialX: null,
      initialY: null,
      xOffset: 0,
      yOffset: 0,
    };
  },
  methods: {
    dragStart(event) {
      console.log('start');
      const dragItem = document.querySelector('.pip');
      if (event.type === 'touchstart') {
        this.initialX = event.touches[0].clientX - this.xOffset;
        this.initialY = event.touches[0].clientY - this.yOffset;
      } else {
        this.initialX = event.clientX - this.xOffset;
        this.initialY = event.clientY - this.yOffset;
      }

      if (event.target === dragItem) {
        this.active = true;
      }
    },
    drag(event) {
      console.log('drag');
      const dragItem = document.querySelector('.pip');
      if (this.active) {
        event.preventDefault();

        if (event.type === 'touchmove') {
          this.currentX = event.touches[0].clientX - this.initialX;
          this.currentY = event.touches[0].clientY - this.initialY;
        } else {
          this.currentX = event.clientX - this.initialX;
          this.currentY = event.clientY - this.initialY;
        }

        this.xOffset = this.currentX;
        this.yOffset = this.currentY;

        this.setTranslate(this.currentX, this.currentY, dragItem);
      }
    },
    dragEnd() {
      console.log('end');
      this.initialX = this.currentX;
      this.initialY = this.currentY;
      this.active = false;
      // event.target.style.bottom = '0px';
      // event.target.style.top = `${event.clientY - event.target.offsetHeight / 2}px`;
      // event.target.style.left = `${event.clientX - event.target.offsetWidth / 2}px`;
      // console.log(event);
    },
    setTranslate(xPos, yPos, el) {
      el.style.transform = "translate3d(' + xPos + 'px, ' + yPos + 'px, 0)";
    },
javascript html vue.js drag-and-drop drag
1个回答
0
投票

同样的问题,你解决了吗?

© www.soinside.com 2019 - 2024. All rights reserved.