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}` )
          }
        })
      })
    },
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值