search
HomeWeb Front-endJS TutorialUse Element-UI Table to implement drag and drop function

This time I will bring you the use of Element-UI Table to implement the drag and drop function. What are the precautions for using the Element-UI Table to implement the drag and drop function? The following is a practical case, let's take a look.

Element-UI’s Table component is very powerful, but our needs are even more powerful...

A simple and crude rendering:

1. Data-driven

The traditional drag effect is based on modification through mousedown, mousemove, mouseup events Delete the dom node

But Vue is a data-driven front-end framework, you should try to avoid operating the dom during development

And the Table component of Element-UI is very rigorously encapsulated, so it is easy to directly operate the dom Unpredictable bugs occur

So my core idea is:Render the table header (column) through an array, and then modify the order of the array, thereby modifying the column sorting of the list

template part:

 <p>
 <el-table>
  <slot></slot>
  <el-table-column>
  </el-table-column>
 </el-table>
 </p>

The above data is the list data collection, option is the Table component configuration item, header is the table header data collection, passed in by the parent component

props: {
 data: {
  default: function () {
  return []
  },
  type: Array
 },
 header: {
  default: function () {
  return []
  },
  type: Array
 },
 option: {
  default: function () {
  return {}
  },
  type: Object
 }
 }

Configuration items can be deleted according to the Element-UI api

But several parameters are required inside the component:

1. header-cell-class-name

Bound a function to dynamically add a class to the header cell to achieve the dotted line effect during dragging.

2. column-key

is bound to the index of the header array and is used to determine the subscript of the header element that needs to be modified

3. render-header

Header rendering function is used to add custom methods to monitor mousemove and other related events

2. Record dragging status

Several key parameters need to be recorded during the dragging process:

data () {
 return {
  tableHeader: this.header,
  dragState: {
  start: -1, // 起始元素的 index
  end: -1, // 结束元素的 index
  move: -1, // 移动鼠标时所覆盖的元素 index
  dragging: false, // 是否正在拖动
  direction: undefined // 拖动方向
  }
 }
 }

In addition, the parent element passes in a header data header, but this data will be modified after the dragging is completed

It is not recommended to directly modify the data of the parent element in the child component, so a tableHeader is initialized here to host the header data header

But in order to allow the tableHeader to respond to the modification when the header is modified, it is necessary Add a monitor watch

 watch: {
 header (val, oldVal) {
  this.tableHeader = val
 }
 }

3. Customize the header

The Table component of Element-UI In order to realize the function of [drag the border to modify the column width], The three events of mousemove, mouseup, and mousedown are not exposed

So you need to customize the header and manually add the mouse event processing function, which requires usingrenderHeader() Method

renderHeader (createElement, {column}) {
  return createElement(
  'p', {
   'class': ['thead-cell'],
   on: {
   mousedown: ($event) => { this.handleMouseDown($event, column) },
   mouseup: ($event) => { this.handleMouseUp($event, column) },
   mousemove: ($event) => { this.handleMouseMove($event, column) }
   }
  }, [
   // 添加 <a> 用于显示表头 label
   createElement('a', column.label),
   // 添加一个空标签用于显示拖动动画
   createElement('span', {
   'class': ['virtual']
   })
  ])
 },</a>

Among the three mouse events, the first parameter is the event object, and the second is the header object

In the corresponding processing function, you can pass column.columnKey Get the corresponding header element subscript index

Empty label is used to display the animation during dragging (Dotted line)

4. Event processing

When the mouse is pressed, the starting column is recorded. When the mouse is lifted, the ending column is recorded. The drag direction is calculated based on the difference between the two.

Then the header data is reordered according to the positions of the starting column and the ending column, so as to realize column dragging.

The processing function of the dragging process is as follows:

// 按下鼠标开始拖动
handleMouseDown (e, column) {
 this.dragState.dragging = true
 this.dragState.start = parseInt(column.columnKey)
 // 给拖动时的虚拟容器添加宽高
 let table = document.getElementsByClassName('w-table')[0]
 let virtual = document.getElementsByClassName('virtual')
 for (let item of virtual) {
 item.style.height = table.clientHeight - 1 + 'px'
 item.style.width = item.parentElement.parentElement.clientWidth + 'px'
 }
},

// 鼠标放开结束拖动
handleMouseUp (e, column) {
 this.dragState.end = parseInt(column.columnKey) // 记录起始列
 this.dragColumn(this.dragState)
 // 初始化拖动状态
 this.dragState = {
 start: -1,
 end: -1,
 move: -1,
 dragging: false,
 direction: undefined
 }
},

// 拖动中
handleMouseMove (e, column) {
 if (this.dragState.dragging) {
 let index = parseInt(column.columnKey) // 记录起始列
 if (index - this.dragState.start !== 0) {
  this.dragState.direction = index - this.dragState.start  min && i <p style="text-align: left;"><strong>5. Dotted line effect</strong></p><p style="text-align: left;">During the dragging process, change the header status of the current column through the mousemove event</p><p style="text-align: left;">Then use <span style="color: #3366ff"><strong>headerCellClassName </strong></span>Dynamic modification of its class</p><pre class="brush:php;toolbar:false">headerCellClassName ({column, columnIndex}) {
 return (columnIndex - 1 === this.dragState.move ? `darg_active_${this.dragState.direction}` : '')
}

This class will be added to the header cell

. Use this class to add the above empty label The dotted line can

Post the complete style I wrote myself (using sass as the compilation tool):

<style>
.w-table {
 .el-table th {
 padding: 0;
 .virtual{
  position: fixed;
  display: block;
  width: 0;
  height: 0;
  margin-left: -10px;
  z-index: 99;
  background: none;
  border: none;
 }
 &.darg_active_left {
  .virtual {
  border-left: 2px dotted #666;
  }
 }
 &.darg_active_right {
  .virtual {
  border-right: 2px dotted #666;
  }
 }
 }
 .thead-cell {
 padding: 0;
 display: inline-flex;
 flex-direction: column;
 align-items: left;
 cursor: pointer;
 overflow: initial;
 &:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
 }
 }
 &.w-table_moving {
 .el-table th .thead-cell{
  cursor: move !important;
 }
 .el-table__fixed {
  cursor: not-allowed;
 }
 }
}</style>

6. Parent component call

<template>
<p>
 <wtable>
 <el-table-column>
 </el-table-column>
 </wtable>
</p>
</template>

<script>
import wTable from &#39;@/components/w-table.vue&#39;
export default {
 name: &#39;Table&#39;,
 data () {
 return {
  tableOption: {
  border: true,
  maxHeight: 500
  },
  tableHeader: [{
  prop: &#39;name&#39;,
  label: &#39;姓名&#39;,
  sortable: true,
  sortMethod: this.handleNameSort
  }, {
  prop: &#39;province&#39;,
  label: &#39;省份&#39;,
  minWidth: &#39;120&#39;
  }, {
  prop: &#39;city&#39;,
  label: &#39;市区&#39;,
  minWidth: &#39;120&#39;
  }, {
  prop: &#39;address&#39;,
  label: &#39;地区&#39;,
  minWidth: &#39;150&#39;
  }, {
  prop: &#39;zip&#39;,
  label: &#39;邮编&#39;,
  minWidth: &#39;120&#39;
  }],

  tableData: [{
  date: &#39;2016-05-03&#39;,
  name: &#39;王小虎&#39;,
  province: &#39;上海&#39;,
  city: &#39;普陀区&#39;,
  address: &#39;上海市普陀区金沙江路 1518 弄&#39;,
  zip: 200333
  }, {
  date: &#39;2016-05-02&#39;,
  name: &#39;王小虎&#39;,
  province: &#39;上海&#39;,
  city: &#39;普陀区&#39;,
  address: &#39;上海市普陀区金沙江路 1518 弄&#39;,
  zip: 200333
  }, {
  date: &#39;2016-05-04&#39;,
  name: &#39;王小虎&#39;,
  province: &#39;上海&#39;,
  city: &#39;普陀区&#39;,
  address: &#39;上海市普陀区金沙江路 1518 弄&#39;,
  zip: 200333
  }, {
  date: &#39;2016-05-01&#39;,
  name: &#39;王小虎&#39;,
  province: &#39;上海&#39;,
  city: &#39;普陀区&#39;,
  address: &#39;上海市普陀区金沙江路 1518 弄&#39;,
  zip: 200333
  }, {
  date: &#39;2016-05-08&#39;,
  name: &#39;王小虎&#39;,
  province: &#39;上海&#39;,
  city: &#39;普陀区&#39;,
  address: &#39;上海市普陀区金沙江路 1518 弄&#39;,
  zip: 200333
  }, {
  date: &#39;2016-05-06&#39;,
  name: &#39;王小虎&#39;,
  province: &#39;上海&#39;,
  city: &#39;普陀区&#39;,
  address: &#39;上海市普陀区金沙江路 1518 弄&#39;,
  zip: 200333
  }]
 }
 },
 methods: {
 handleNameSort () {
  console.log(&#39;handleNameSort&#39;)
 }
 },
 components: {
 wTable
 }
}
</script>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Progressbar component practical case analysis

How to optimize the Vue project

The above is the detailed content of Use Element-UI Table to implement drag and drop function. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools