vue3使用vuedraggable实现(表格)拖拽排序

1.安装插件

yarn add vuedraggable@next

npm i -S vuedraggable@next

2.举个栗子

<draggable 
  v-model="myArray" 
  group="people" 
  @start="drag=true" 
  @end="drag=false" 
  item-key="id">
  <template #item="{element}">
    <div>{{element.name}}</div>
   </template>
</draggable>

简单表格(带表头)
需要加 With header slot

<table align="left">      
    <Draggable
      :list="list"
      :animation="100"
      item-key="id"
      class="list-group"
      :forceFallback="true"
      ghost-class="ghost"
      @change="onMoveCallback"
      :move="getdata"
      draggable=".tr"
    >        
      <template #item="{ element }">
      <tr class="tr">
        <td>     
          {{ element.userId }}  
        </td>
        <td>
          {{ element.nickName }}
        </td>
        <td>     
          {{ element.sex }}  
        </td>        
      </tr>       
      </template>
      <!-- 表头 -->
      <template #header>
        <tr>
        <th>userId</th>
        <th>nickName</th>
        <th>sex</th>    
      </tr>
      </template>      
    </Draggable>
    </table>

当然,头可插入,尾部一样,如有需要也可添加

<draggable v-model="myArray" item-key="id">
  <template #item="{element}">
    <div> {{element.name}} </div>
  </template>
  <template #header>
    <button @click="addPeople">Add</button>
  </template>
  <template #footer>
    <button @click="addPeople">Add</button>
  </template>
</draggable>

3.简单表格拖拽功能:

<template>
  <div class="contain">
    <table align="left">      
    <Draggable
      :list="list"
      :animation="100"
      item-key="id"
      class="list-group"
      :forceFallback="true"
      ghost-class="ghost"
      @change="onMoveCallback"
      :move="getdata"
      draggable=".tr"
    >        
      <template #item="{ element }">
      <tr class="tr">
        <td>     
          {{ element.userId }}  
        </td>
        <td>
          {{ element.nickName }}
        </td>
        <td>     
          {{ element.sex }}  
        </td>
      </tr>       
      </template>
      <!-- 表头 -->
      <template #header>
        <tr>
        <th>userId</th>
        <th>nickName</th>
        <th>sex</th>
      </tr>
      </template>      
    </Draggable>
    </table>
  </div>
</template>

<script setup lang="ts">
import {ref,reactive} from 'vue'
import Draggable from 'vuedraggable'
import { GetUserList } from '/@/api/sys/user';
    let list = ref([]);
    const onMoveCallback = (val) => {
      console.log('拖动前的索引 :' + val.moved.newIndex);
      console.log('拖动后的索引 :' + val.moved.oldIndex);
    };
    const getdata = (val) => {
      console.log(val.draggedContext.element.id);
    };

    const getList = async () => {//获取列表接口};
	getList();
</script>

<style  scoped>
.contain{
  margin: 20px;
  padding: 20px;
  min-width: 1120px;
}
table{
  background: #fefefe;
}
td,th{
  padding: 16px;
  border: 1px solid #ccc;
}
</style>

其他:
vue3用法,官方文档及说明
vue2用法,官方文档及说明
vue.draggable中文文档

你可能感兴趣的:(vue,工具,javascript,vue.js,前端)