[Vuejs]-Dragging an element inside a div but the element flashes when dragged

1👍

You can calculate the position as an offset from start position, and then update it based on the movement. This will allow to draw by any part. You can (and should IMHO) attach and remove the event handlers dynamically.

Here is what that might look like:

<template>
  <div id="app">
    <div id="board">
      <div
        class="draggableItem"
        @mousedown="dragStart"
        :style="{top: this.top + 'px', left: this.left + 'px'}"
      >This should be draggable</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data: function() {
    return {
      isDragging: false,
      top: 50,
      left: 50,
      startTop: 0,
      startLeft: 0
    };
  },
  methods: {
    dragOver: function(e) {
      if (this.isDragging) {
        this.top = e.clientY - this.startTop;
        this.left = e.clientX - this.startLeft;
      }
    },
    dragStart: function(e) {
      window.addEventListener('mousemove', this.dragOver)
      window.addEventListener('mouseup', this.dragStop)
      this.isDragging = true;
      this.startTop = e.clientY - this.top;
      this.startLeft = e.clientX - this.left;
    },
    dragStop: function(e) {
      window.removeEventListener('mousemove', this.dragOver)
      window.removeEventListener('mouseup', this.dragStop)
      this.isDragging = false;
    }
  }
};
</script>
👤Daniel

Leave a comment