Home Web Front-end JS Tutorial How to develop Vue drag and drop components

How to develop Vue drag and drop components

May 30, 2018 am 11:07 AM
develop components conduct

This time I will show you how to develop Vue drag and drop components, and what are the precautions for developing Vue drag and drop components. The following is a practical case, let's take a look.

Why choose Vue?

Main reasons: For front-end development, compatibility is one of the issues we must consider. Our project does not need to be compatible with lower version browsers. The project itself is also data-driven. In addition, Vue itself has the following main features:

•Use virtual DOM;

•Lightweight framework;
•Efficient
data binding;•Flexible Component system;
•Complete development ecological chain.

These are some reasons why we choose the Vue framework.

Why should it be encapsulated into a Vue component?

The main purpose is to improve the reusability and maintainability of the code.

•Reusability: After componentization, some styles and logic are differentiated and reflected by configuring parameters, so the configurability of parameters improves the reuse rate and flexibility of components.

•Maintainability: After componentization, the internal logic of the component is only responsible for the component, and the external logic is only adapted through configuration parameters. This improves the logic clarity of the code and can quickly locate code problems. place.

Illustration of component-based building page:

As can be seen from the above figure, in Vue, the so-called component-based building page, in simple terms, the page is actually It is built from functionally independent components. These components can be combined and nested to form our page.

Component composition

The following is a completed component composition:

// 组件内模板
// 组件内逻辑代码
<script type="text/javascript"></script>
// 组件内封装的样式
<style lang="scss" scoped></style>
Copy after login

Develop Vue Mobile Take the drag component as an example

Principle of drag

While the finger is moving, the position of the element, that is, the top and left values, is changed in real time. Make the element move with the movement of your finger.

Drag implementation

•When starting dragging: Get the coordinates clientX, clientY of the contact point relative to the entire view area ; Get the distance between the element and the upper and left sides of the view initTop, initLeft; Calculate the distance between the contact point and the upper and left sides of the element elTop = clientY - initTop, elLeft = clientX - initLeft;

• During dragging: pass currTop = clientY - elTop, currLeft = clientX - elLeft obtains the distance value of the element from the upper and left sides of the view in real time, and assigns the value to the element, so that the element moves with the movement of the finger;
• End of dragging, position the element .

Implementation in Vue

The biggest difference when using Vue is that we hardly operate the DOM and must make full use of Vue’s data Driver to implement drag and drop functionality. In this case, we only need to drag the element in the vertical direction, so only vertical movement is considered.

In the above figure, the drag area list is rendered through the dragList in data. The code is as follows:

template:
<p class="drag-title">拖拽可调整顺序</p>
<ul class="drag-list">
 <li class="drag-item">{{item.txt}}</li>
</ul>
script:
 
export default {
data() {
return {
dragList:null
}
},
created() {
this.dragList = [
{
isDrag: false,
txt: '列表1',
isShow: false
}
...
]
},
}
Copy after login
Assume that we drag the element from position 1 to position 3. Essentially, the order of the array has changed. It is necessary to mention the biggest feature of Vue: data-driven.

The so-called data-driven means that when the data changes, the user interface changes accordingly by modifying the data status. Developers do not need to manually modify the DOM.

Vue's data drive is implemented through the MVVM framework. The MVVM framework mainly contains three parts: Model, View, and Viewmodel.

– Model: data part;

– View: view part;
– Viewmodel:
middleware that connects view and data.

Following this line of thinking, we know:

– oldIndex:元素在数组中的初始索引index;
– elHeight:单个元素块的高;
– currTop = clientY - elTop:元素在拖动过程中距离可视区上侧距离;
– currTop - initTop > 0:得知元素是向上拖拽;
– currTop - initTop < 0:得知元素是向下拖拽。

我们以向下拖拽来说:

– 首先,我们要在拖拽结束事件touchend中判断元素从拖动开始到拖动结束时拖动的距离。若小于某个设定的值,则什么也不做;
– 然后,在touchmove事件中判断,若(currTop - initTop) % elHeight>= elHeight/2成立,即当元素拖至另一个元素块等于或超过1/2的位置时,即可将元素插入到最新的位置为newIndex = (currTop - initTop) / elHeight + oldIndex。
– 最后,若手指离开元素,那么我们在touchend事件中,通过this.dragList.splice(oldIndex, 1),this.dragList.splice(newIndex, 0, item)重新调整数组顺序。页面会根据最新的dragList渲染列表。

写到这里,我们俨然已经用Vue实现了移动端的拖拽功能。但是拖拽体验并不好,接下来,我们对它进行优化。

优化点:我们希望,在元素即将可能落到的位置,提前留出一个可以放得下元素的区域,让用户更好的感知拖拽的灵活性。

方案:(方案已被验证是可行的)将li的结构做一下修改,代码如下:

<ul>
 <li class="drag-item">
<p class="leave-block"></p>
// 向上拖拽时留空
<p class="">{{item.txt}}</p>
<p class="leave-block"></p>
// 向下拖拽时留空</li>
</ul>
Copy after login

•拖拽开始:将元素的定位方式由static设置为absolute,z-index设置为一个较大的值,防止元素二次拖拽无效;

•拖拽过程中:将元素即将落入新位置的那个li下p的item.isShow设置为true,其他li下p的item.isShow均设置为false;

•拖拽结束:将所有li下p的item.isShow 均设置为false,将元素定位方式由absolute设置为static。

贴一段伪代码:

touchStart(e){
// 获取元素距离视口顶部的初始距离
initTop = e.currentTarget.offsetTop;
// 开始拖动时,获取鼠标距离视口顶部的距离
initClientY = e.touches[0].clientY;
// 计算出接触点距离元素顶部的距离
elTop = e.touches[0].clientY - initTop;
},
touchMove(index, item, e){
// 将拖拽结束时,给元素设置的static定位方式移除,防止元素二次拖拽无效
e.target.classList.remove('static');
// 给拖拽的元素设置绝对定位方式
e.target.classList.add('ab');
// 获取元素在拖拽过程中距离视口顶部距离
currTop = e.touches[0].clientY - elTop;
// 元素在拖拽过程中距离视口顶部距离赋给元素
e.target.style.top = currTop ;
// 获取元素初始位置
oldIndex = index;
// 获取拖拽元素
currItem = item;
// 若元素已经拖至区域外
if(e.touches[0].clientY > (this.dragList.length) * elHeight){
// 将元素距离上侧的距离设置为拖动区视图的高
currTop = (this.dragList.length) * elHeight;
return;
}
// 向下拖拽
if(currTop > initTop ){
// 若拖拽到大于等于元素的一半时,即可将元素插入到最新的位置
if((currTop - initTop) % elHeight>= elHeight / 2){
// 计算出元素拖到的最新位置
newIndex = Math.round((currTop - initTop) / elHeight) + index;
// 确保新元素的索引不能大于等于列表的长度
if(newIndex < this.dragList.length){
// 将所有列表留空处隐藏
for(var i = 0;i< this.dragList.length;i++){
this.dragList[i].isShow = false;
}
// 将元素即将拖到的新位置的留空展示
this.dragList[newIndex].isShow = true;
}
else {
return;
}
}
}
// 向上拖拽,原理同上
if(currTop < initTop){ ... } }, touchEnd(e){ // 若拖动距离大于某个设定的值,则按照上述,执行相关代码 if(Math.abs(e.changedTouches[0].clientY - initClientY ) > customVal){
this.dragList.splice(oldIndex, 1);
this.dragList.splice(newIndex, 0, currItem);
for(var i = 0;i< this.dragList.length;i++){
this.dragList[i].isShow = false;
this.dragList[i].isShowUp = false;
}
}
e.target.classList.remove('ab');
e.target.classList.add('static');
}
Copy after login

优化后,如下图所示:

以上便是用Vue实现移动端拖拽组件的过程。我们知道,有些项目是需要在PC端用Vue实现此功能。这里简单提一下PC与移动端的区别如下:

•PC端可以使用的事件组有两种:第一种:H5新特性draggable,dragstart,drag,dragend;第二种:mousedown,mousemove,mouseup;

•PC端获取鼠标坐标是通过e.clientX,clientY,区别于移动端的e.touches[0].clientX,e.touches[0].clientY。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样操作vue中$emit 与$on父子与兄弟组件通信

如何使用node命令方式启动修改端口

The above is the detailed content of How to develop Vue drag and drop components. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Summary of the five most popular Go language libraries: essential tools for development Summary of the five most popular Go language libraries: essential tools for development Feb 22, 2024 pm 02:33 PM

Summary of the five most popular Go language libraries: essential tools for development, requiring specific code examples. Since its birth, the Go language has received widespread attention and application. As an emerging efficient and concise programming language, Go's rapid development is inseparable from the support of rich open source libraries. This article will introduce the five most popular Go language libraries. These libraries play a vital role in Go development and provide developers with powerful functions and a convenient development experience. At the same time, in order to better understand the uses and functions of these libraries, we will explain them with specific code examples.

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Understanding VSCode: What is this tool used for? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

&quot;Understanding VSCode: What is this tool used for?&quot; 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

Which Linux distribution is best for Android development? Which Linux distribution is best for Android development? Mar 14, 2024 pm 12:30 PM

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

See all articles