vue uses sortable to implement el table drag and drop sorting function

  • 2021-10-15 09:43:04
  • OfStack

This article introduces you to vue using sortable to implement el-table drag-and-drop sorting function, which is as follows:

npm download:


npm install sortablejs --save

Introduce:


import Sortable from "sortablejs";

Code:


<template>
 <div class="table">
 <el-table ref="dragTable" :data="tableData" border :row-class-name="tableRowClassName">
 <el-table-column prop="date" label=" Date "></el-table-column>
 <el-table-column prop="name" label=" Name "></el-table-column>
 <el-table-column prop="address" label=" Address "></el-table-column>
 <el-table-column label=" Operation ">
 <template>
 <el-button class="move" type="text" size="small"> Drag   Tug </el-button>
 </template>
 </el-table-column>
 </el-table>
 </div>
</template>
<script>
import Sortable from "sortablejs";
export default {
 data() {
 return {
 tableData: [
 {
 id: "1",
 name: "text_1",
 date: "1111-11-11",
 address: " Test _1",
 },
 {
 id: "2",
 name: "text_2_ Do not drag ",
 date: "2222-22-22",
 address: " Test _2_ Do not drag ",
 disabled: true,
 },
 {
 id: "3",
 name: "text_3",
 date: "3333-33-33",
 address: " Test _3",
 },
 {
 id: "4",
 name: "text_4",
 date: "4444-44-44",
 address: " Test _4",
 },
 {
 id: "5",
 name: "text_5",
 date: "5555-55-55",
 address: " Test _5",
 },
 ],
 };
 },
 methods: {
 //  Create sortable Instances 
 initSortable() {
 //  Get a table row Parent node of 
 const ele = this.$refs.dragTable.$el.querySelector(
 ".el-table__body > tbody"
 );
 //  Create a drag instance 
 let dragTable = Sortable.create(ele, {
 animation: 150, // Animation 
 handle: ".move", // Specify a drag target, which can be clicked to drag elements ( In this example, set the action button drag )
 filter: ".disabled", // Specifies a class name that cannot be dragged ( el-table Can be passed in row-class-name Set the row's class ) 
 dragClass: "dragClass", // Set the drag-and-drop style class name 
 ghostClass: "ghostClass", // Set the drag-and-drop docking style class name 
 chosenClass: "chosenClass", // Sets the selected style class name 
 //  Start dragging events 
 onStart: () => {
 console.log(" Start dragging ");
 },
 //  End drag event 
 onEnd: (e) => {
 console.log(
 " End drag ",
 ` Drag the front index ${e.oldIndex}--- Index after dragging ${e.newIndex}`
 );
 },
 });
 },
 //  Setup table row Adj. class
 tableRowClassName({ row }) {
 if (row.disabled) {
 return "disabled";
 }
 return "";
 },
 },
 mounted() {
 this.initSortable();
 },
};
</script>
<style lang='scss'>
//  Drag and drop 
.dragClass {
 background: rgba($color: #41c21a, $alpha: 0.5) !important;
}
//  Dock 
.ghostClass {
 background: rgba($color: #6cacf5, $alpha: 0.5) !important;
}
//  Select 
.chosenClass:hover > td {
 background: rgba($color: #f56c6c, $alpha: 0.5) !important;
}
</style>

Related articles: