Home >Web Front-end >Vue.js >How to use Vue3 to implement an elegant element dragging function

How to use Vue3 to implement an elegant element dragging function

WBOY
WBOYforward
2023-05-13 18:46:061841browse

Recommend several useful tools

  • var-conv is a quick conversion tool for code variable names suitable for VSCode IDE

  • generator-vite-plugin Quickly generates Vite plug-in template projects

  • generator-babel-plugin Quickly generates Babel plug-in template projects

Get to the point

Element dragging is a typical front-end learning case, which requires a certain understanding of JavaScript events. I also learned this in my recent work I picked up this content again and explained it clearly by dragging the element once in a declarative programming style framework such as Vue3.

PS: The centered attribute in the Vue3 template global style may cause experimental interference, please be careful! ! !

The position and movement of elements

When implementing element dragging, we use the mouse event, and the callback of the mouse event The position of the element when the current event occurs can be obtained in the function. The corresponding attributes are clientX and clientY in MouseEvent. We will read these two later. Property to update the element's position in real time. It is recommended to use

translate

in transform to move the element first, instead of modifying top and left## of the element. # Attributes will not cause changes to the element layout, avoiding the performance impact caused by reflow and redrawing.

PS: There is an article about the use and experience of translate in MDN, you can feel it.

Define three sets of coordinates

define a set of coordinates used to record the initial position of the element (

originalPosition) and the pointer when the element is pressed The coordinates on the element (mousedownOffset) and a set of coordinates that update in real time as the element moves (elementPosition).

Record the coordinates of the initial position of the element. The origin is located in the upper left corner of the page. It is used to restore the position of the dragged element after initialization and dragging. The fixed value does not change:

const originalPosition = reactive({
  x: 10,
  y: 10,
})

The coordinates of the pointer on the element when the element is pressed. The origin is located at the upper left corner of the dragged element. It is obtained by the coordinates of the pointer when pressed - the initial offset position of the element:

const mousedownOffset = reactive({
  x: 0,
  y: 0,
})

The element moves in real time The updated coordinates, the origin is located in the upper left corner of the page, and the initial value should be the same as

originalPosition. When the mousemove event occurs, the real-time coordinates of the pointer - mousedownOffset are obtained:

const elementPosition = reactive({
  x: 0,
  y: 0,
})

How to use Vue3 to implement an elegant element dragging function

PS: When the origin is the upper left corner of the page, point 1 in the figure represents

originalPosition or elementPosition, point 2 The point represents the coordinates when the pointer is pressed. When the origin is point 1, point 2 in the figure represents mousedownOffset;

Register mousedown event

When implementing element dragging, you only need to add the

mousedown event to the dragged element. Remember to clear the listening event after using it. The habit of appearing in pairs must be developed.

If you add

mousemove and mouseup to the dragged element, you will find that there is an out-of-control phenomenon.

After the page is loaded, first reset the default position of the dragged element, and add the

mousedown event. After the component is unloaded, delete the mousedown event:

const restore = () => {
  elementPosition.x = originalPosition.x;
  elementPosition.y = originalPosition.y;
}

onMounted(() => {
  restore();
  floatButton.value.addEventListener('mousedown', onMousedown, true);
})

onUnmounted(() => {
  floatButton.value.removeEventListener('mousedown', onMousedown, true);
})

The core of drag and drop

The reason why we choose

Vuejs is because it is a MVVM type framework, our focus In terms of declaration, the framework is responsible for the internal operating mechanism, so in the following event processing, you only need to update the three sets of coordinates declared at the beginning in the corresponding event.

At

onMousedown, the coordinates of the pointer on the dragged element are obtained through the coordinates of the pointer - the coordinates of the initial position of the dragged element, onMousedown When document, add mousemove and mouseup events:

const onMousedown = (event: MouseEvent) => {
  event.stopPropagation();
  
  mousedownOffset.x = event.clientX - originalPosition.x;
  mousedownOffset.y = event.clientY - originalPosition.y;
  
  document.addEventListener('mousemove', onMousemove, true);
  document.addEventListener('mouseup', onMouseup, true);
}

When

onMousemove, pass the coordinates of the pointer - The position of the pointer on the dragged element gets the distance between the upper left corner of the dragged element and the upper left corner of the page, and is updated to elementPosition:

const onMousemove = (event: MouseEvent) => {
  event.stopPropagation();
  
  elementPosition.x = event.clientX - mousedownOffset.x;
  elementPosition.y = event.clientY - mousedownOffset.y;
}

in

onMouseup , the main thing to do is to remove the two events registered at onMousemove for document. It should be noted that the removed events must be the same event, that is, events with consistent references. , it is recommended to assign the corresponding processing event to a variable for use. Finally, the position of the dragged element can be restored after the drag is completed:

const onMouseup = (event: MouseEvent) => {
  event.stopPropagation();
  document.removeEventListener('mousemove', onMousemove, true);
  document.removeEventListener('mouseup', onMouseup, true);
  restore();
}

Supplement other parts of the code and demonstration
<div 
 ref="floatButton"
 class="float-button"
 :style="{
    &#39;transition-duration&#39;: &#39;0.1s&#39;,
    transform: `translate(${elementPosition.x}px, ${elementPosition.y}px)`
  }">
</div>

.float-button {
  position: absolute;
  width: 42px;
  height: 42px;
  background: red;
  border-radius: 5px;
  user-select: none;
  background-image: url(../assets/taobao.svg);
  background-size: cover;
}
<p><img src="https://img.php.cn/upload/article/000/887/227/168397476873752.jpg" alt="How to use Vue3 to implement an elegant element dragging function"></p>

The above is the detailed content of How to use Vue3 to implement an elegant element dragging function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete