search
HomeWeb Front-endVue.jsHow to use Vue3 to implement an elegant element dragging function

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="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/887/227/168397476873752.jpg?x-oss-process=image/resize,p_40" class="lazy" 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:亿速云. If there is any infringement, please contact admin@php.cn delete
The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor