vue3拖拽排序使用Sortable,获取拖拽排序之后的数据

1.安装Sortable

npm install sortablejs

2.导入

import Sortable from 'sortablejs'

3.使用

// html
 <div id="example" class="list-group">
    <template v-for="(element, index) in 6" :key="index">
        <div>item{
   
   {index + 1}}</div>
    </template>
  </div>

// js

// dom获取节点
 const el = document.getElementById('example')

const sortableHtml = new Sortable(el, {
    animation: 150,
    // 拖拽时预览图样式
    ghostClass: 'blue-background-class',
    
    // 具体配置见http://www.sortablejs.com/options.html
  })

Sortable.js中文网|配置Sortable相关配置:Sortable.js中文网|配置

vue3拖拽使用Sortable,获取拖拽之后的数据,Sortable拖拽结束之后获取的数据是没有改变的

 通过绑定onEnd回调方法,获取返回的evt对象,对象中存在oldIndex及newIndex参数,虽然拖拽之后获取的数据是没有改变的,而且此时更改绑定的数据会出现页面拖拽排序之后的序列出现错乱,所以我们可以在页面加载时深拷贝原始数据

onEnd方法返回的index参数是更改之后的,即index参数是实时更新的,所以我们可以通过index来对数据进行更改

const newFormTable = ref<object[]>([])
onMounted(() => {
  // 深拷贝数据
  newFormTable.value = JSON.parse(JSON.stringify(formTable。vallue))
  const el = document.getElementById('example')
  const sortableHtml = new Sortable(el, {
    animation: 150,
    // 拖拽时预览图样式
    ghostClass: 'blue-background-class',
    // 拖拽结束
    onEnd: (evt) => {
      // 通过index更改数据,获取拖拽排序之后的数据
      const changeData = newFormTable.value.splice(evt.oldIndex || 0, 1)
      newFormTable.value.splice(evt.newIndex || 0, 0, changeData[0])
    }
  })
})

猜你喜欢

转载自blog.csdn.net/q12as/article/details/132322770
今日推荐