vue3中使用sortablejs + el-table中实现拖动行(切换路由回来后导致不能拖动的问题解决)

vue3中使用sortablejs + el-table中实现拖动行

一、安装:yarn install --save sortablejs
二、使用示例:

<script lang="ts" setup>
import {
    
     Plus } from '@element-plus/icons-vue'
import Sortable from 'sortablejs'
const tableData = ref([
  {
    
    
    date: '2016-05-03',
    name: '111',
    address: 'admin123',
  },
  {
    
    
    date: '2016-05-02',
    name: '222',
    address: 'admin123',
  },
  {
    
    
    date: '2016-05-04',
    name: '333',
    address: 'admin123',
  },
  {
    
    
    date: '2016-05-01',
    name: '444',
    address: 'admin123',
  },
])
const req_table = ref(null)
const initSortable = () => {
    
    
  nextTick(() => {
    
    
    const table = req_table.value.querySelector('.el-table__body-wrapper tbody')
    // const table = document.querySelector('.reqtable .el-table__body-wrapper tbody') // 使用这种方法路由切换后再切换回来获取不到
    const dragTable = Sortable.create(table, {
    
    
      handle: '.move', // 指定拖拽目标,拖拽此目标才可拖拽元素(本示例中为plus图标),不设置此属性则拖动table行元素(tbody子元素)
      onEnd: ({
    
     newIndex, oldIndex }) => {
    
    
        if (oldIndex !== newIndex)
          console.log('拖动成功', `元素拖动前索引${
    
    oldIndex}---元素拖动后索引${
    
    newIndex}`)
      },
    })
  })
}
nextTick(() => {
    
    
  initSortable()
})
</script>
<template>
  <div ref="req_table">
    <el-table row-key="id" mt-9px :data="tableData" style="width: 100%" border>
      <el-table-column label="排序" width="50">
        <template #default>
          <Plus size="10px" cursor="pointer" class="move" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="date" label="日期" />
    </el-table>
  </div>
</template>

const table = document.querySelector(‘.reqtable .el-table__body-wrapper tbody’) // 使用这种方法路由切换后再切换回来获取不到dom元素,取到的值为null

vue2中拖动div

<div class="sign_step" ref="sortitem">
    <div class="move">item1</div>
    <div class="move">item1</div>
    <div class="move">item1</div>
  </div>
initSortable () {
    
    
      const that = this
      this.$nextTick(()=>{
    
    
        const sort = that.$refs.sortitem
        Sortable.create(sort,{
    
    
          //动画效果
          animation: 1000,
          // 是否执行两个盒子之间互换
          group:'box',
          handle: '.move', // 指定拖拽目标
          onEnd: ({
     
      newIndex, oldIndex }) => {
    
    
            console.log('拖动成功', `元素拖动前索引${
      
      oldIndex}---元素拖动后索引${
      
      newIndex}` )
          }
        })
      })
    },

猜你喜欢

转载自blog.csdn.net/qq_29184685/article/details/126389097
今日推荐