Problem description

Sortable.js is an excellent JS drag library, because it is written by native JS, so the performance is good, also support mobile terminal oh. This article cites two cases to learn.

Example 1: Simple drag and drop

rendering

Code attached

For understanding the comments oh, run copy and paste can be

<! DOCTYPE html><html>

<head>
    <meta charset="utf-8" />
    <title>Sortable.js Drag example</title>
    <meta name="viewport"
        content="Width =device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal UI">
    <! -- Introducing plugins -->
    <script src="https://www.itxst.com/package/sortable/sortable.min.js"></script>
    <style>
        #wrapBox {
            width: 360px;
            /* Drag the height of the container, supported by the height of the drag item */
            height: auto;
        }

        #wrapBox div {
            padding: 8px;
            background-color: #fdfdfd;
            border: solid 1px #eee;
            margin-bottom: 10px;
            /* Add mouse hover style to move style, otherwise not pretty */
            cursor: move;
            font-size: 13px;
        }

        /* Set the mouse press style, add a nice */
        #wrapBox div:active {
            background-color: #eee;
        }
    </style>
</head>

<body>
    <h2>Priority order of deduction:</h2>
    <! Generally speaking, drag structure is: outside a drag container, inside is one after another drag items -->
    <div id="wrapBox">
        <div data-id=1 Industrial and Commercial Bank of China>Industrial and commercial bank of</div>
        <div data-id=2 construction Bank>Construction bank</div>
        <div data-id=3 Bank of China>The bank of China,</div>
        <div data-id=4 Agricultural Bank of China>Agricultural bank of</div>
        <div data-id="5 Bank of Communications">Bank of communications</div>
    </div>
    <script>
        // Get the drag container
        var wrap = document.getElementById('wrapBox');
        // Set the drag rule for the drag item
        var rules = {
            animation: 500.// The animation length of the position change of the element when dragging,
            // Drag the end of the callback function
            onEnd: function (event) {
                console.log('Parameter is drag event object', event);
                // Get the position order of each item in the container after dragging
                var arr = sortable.toArray();
                console.log('Positional sort', arr); }};// Initialize --> add drag rules to the drag container
        var sortable = Sortable.create(wrap, rules);
        Sortable.toarray () gets an array of serialized id attributes for each item element. Sortable.create(wrap, rules) adds drag rules to the drag container
    </script>
</body>

</html>
Copy the code

Example 2 El-Table table drag and drop

There is a detail here, that is, when the header data is dragged, it may lead to the problem of incorrect rendering data. Some bloggers make two header array data, in fact, it is also a solution to the problem. But my humble opinion is slightly troublesome, in fact, a table header array data can be. Just clean it up and reassign it

rendering

Code attached

CNPM install sortablejs –save

Code directly copy and paste can be run to see the effect map, please see comments about the use of oh

<template>
  <div class="myWrap">
    <el-table
      :data="tableBody"
      border
      row-key="id"
      :header-cell-style="{ height: '48px', background: '#FAFAFA', color: '#333333', fontWeight: 'bold', fontSize: '14px', }"
    >
      <! -- Check box -->
      <el-table-column type="selection" width="48" fixed></el-table-column>
      <! -- Serial number column -->
      <el-table-column label="Serial number" type="index" width="50" fixed>
      </el-table-column>
      <! -- table header -->
      <el-table-column
        v-for="(item, index) in tableHeader"
        :key="item.index"
        :prop="item.prop"
        :label="item.label"
      >
      </el-table-column>
    </el-table>
    <br />
    <h3>Header data</h3>
    <pre>{{ tableHeader }}</pre>
    <br />
    <h3>The data table body</h3>
    <pre>{{ tableBody }}</pre>
  </div>
</template>
<script>
// Introduce the sorTableJS plugin, which is the main drag plugin
import Sortable from "sortablejs";
export default {
  data() {
    return {
      // Table header data
      tableHeader: [{label: "Name".prop: "name"}, {label: "Age".prop: "age"}, {label: "Home".prop: "home"}, {label: "Hobby".prop: "hobby"],},// Table body data
      tableBody: [{id: "1".name: "Sun Wukong".age: 500.home: "Flower and Fruit Hill".hobby: "Eat the peach."}, {id: "2".name: "Pig Eight Quit".age: 88.home: "Lao Zhuang Gao".hobby: "Eat steamed stuffed bun"}, {id: "3".name: "Sand Monk".age: 1000.home: "Tongtian River".hobby: "Swimming"}, {id: "4".name: "Tang's monk".age: 99999.home: "Dongtu Datang".hobby: "Prayers",}]}; },mounted() {
    // Column drag initializes
    this.columnDropInit();
    // Row drag initializes
    this.rowDropInit();
  },
  methods: {
    / / drag and drop
    columnDropInit() {
      // The first step is to get the column container
      const wrapperColumn = document.querySelector(
        ".el-table__header-wrapper tr"
      );
      // Step 2, specify the corresponding drag rules for the column container
      this.sortable = Sortable.create(wrapperColumn, {
        animation: 500.delay: 0.onEnd: (event) = > {
          console.log(
            "After the drag is complete, we find that the table header data has not changed, so we need to manually update the table header data.".this.tableHeader
          );
          console.log(
            "Update according to the old index with the new index, which is essentially swapping places.",
            event.oldIndex,
            event.newIndex
          );

          // Then do the index swap
          let tempHableHeader = [...this.tableHeader]; // save a temporary variable header data
          let temp; // Temporary variables are used for swaps
          temp = tempHableHeader[event.oldIndex - 2]; // Notice the -2 because I added two columns to the front of the table (check box column and ordinal column)
          tempHableHeader[event.oldIndex - 2] =
            tempHableHeader[event.newIndex - 2]; // If you do not have these two columns, the serial number is normal, so you do not need to subtract 2
          tempHableHeader[event.newIndex - 2] = temp;

          // Important things say three times!!
          // The table header must be cleared first, and then the next round of the assignment, otherwise it will render errors
          // The table header must be cleared first, and then the next round of the assignment, otherwise it will render errors
          // The table header must be cleared first, and then the next round of the assignment, otherwise it will render errors
          this.tableHeader = []; // You can try it out
          this.$nextTick(() = > {
            this.tableHeader = tempHableHeader; }); }}); },/ / drag and drop
    // I don't think you need to add row drag, because after you add it, you can't double-click the text of the selected row cell, of course, you still need to follow the arrangement of the product manager
    rowDropInit() {
      // Get the row container
      const wrapperRow = document.querySelector(
        ".el-table__body-wrapper tbody"
      );
      const that = this; // Save a pointer
      // The second step is to specify a drag rule for the row container
      Sortable.create(wrapperRow, {
        onEnd({ newIndex, oldIndex }) {
          // Here is another way of distinguishing column drag from above

          // Delete the original item first and save a copy of the original item, because splice returns an array in which the first item is the deleted item
          const currRow = that.tableBody.splice(oldIndex, 1) [0];
          // Then add this item to the new position
          that.tableBody.splice(newIndex, 0, currRow); }}); ,}}};</script>
<style lang='less' scoped>
.myWrap {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 25px;
  /deep/ .el-table {
    .el-table__header-wrapper {
      tr {
        th{// Set drag style to look nicecursor: move;
        }
      }
    }
  }
}
</style>
Copy the code

Bad writing is better than a good memory, take notes

Finally, the official website is attached: www.sortablejs.com/

Or: www.itxst.com/sortablejs/…