vue3 + sortablejs + element plus 实现表格拖动排序

vue3 + sortablejs + element plus 实现表格拖动排序

    • 准备工作
    • 代码
    • 说明

准备工作

下载插件 npm install sortable.js --save (下载的时候注意一下,不要去下载 npm install sortable–save )
因为sortable.js和sortable是不一样的

代码

<template>
 <el-table :data="data.tableData" row-key="date" border style="width: 100%">
     <el-table-column type="index" label="序号" width="180"/>
     <el-table-column prop="date" label="日期" width="180"/>
     <el-table-column prop="name" label="匹配网址" width="180"/>
     <el-table-column prop="address" label="备注"/>
     <el-table-column prop="address" label="操作"/>
   </el-table>
</template>
<script setup>
import {computed, nextTick, onMounted, reactive, watch} from "vue";

import Sortable from 'sortablejs';

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits('update:dialogVisible')

const dialogVisible = computed({
  get: () => props.dialogVisible,
  set: (value) => emits('dialogVisible', value)
})

const data = reactive({
  dictTableKey: '',
  title: '编辑',
  tableData: [
    {
      date: '2016-05-03',
      name: '张三',
      address: 'No. 189, Grove St, Los Angeles',
    },
    {
      date: '2016-05-02',
      name: '里斯',
      address: 'No. 189, Grove St, Los Angeles',
    },
    {
      date: '2016-05-04',
      name: '王五',
      address: 'No. 189, Grove St, Los Angeles',
    },
  ]
})

  nextTick(() => {
    rowDrop();
  });
//行拖拽
const rowDrop = () => {
  const tbody = document.querySelector('.edit .el-table__body-wrapper tbody')
  Sortable.create(tbody, {
    onEnd({ newIndex, oldIndex }) {
      let newList = [...data.tableData]

      const currRow = newList?.splice(oldIndex, 1)[0]
      newList.splice(newIndex, 0, currRow)
      data.tableData = newList
    }
  })
}
</script>
<style scoped lang="scss">

</style>

说明

切记一定要设置el-table的row-key属性,不然会出现视图就近更新的问题,导致视图和数据的排序对不上。

你可能感兴趣的:(vue,vue,elementui,前端)