vue3项目中使用sortablejs实现图片拖拽排序

一、安装依赖

pnpm install sortablejs

二、具体实现代码

1、模板部分 (<template>):图片列表

<div class="imgList flex" ref="uploadImgItem">
      <div v-for="item in imgList" :key="item.id" class="mr-4 imgItem">
        <img :src="item.url" alt="" v-if="item.type === 'image'" />
        <video :src="item.url" v-if="item.type === 'video'"></video>
        <div class="videoMask flex items-center justify-center" v-if="item.type === 'video'">
          <img src="@/assets/icons/105.svg" alt="" />
        </div>
        <div class="deleteImg">
          <img src="@/assets/icons/106.svg" alt="" />
        </div>
      </div>
    </div>

2、脚本部分 (<script>)

引入sortablejs

import Sortable from 'sortablejs'

3、 钩子用于在组件挂载onMounted后初始化拖拽排序功能。

拖拽排序初始化initDragSort 方法使用 SortableJS 库初始化拖拽排序功能,使得图片和视频列表可以通过拖拽来重新排序。

const imgList = ref([
  { id: 1, url: img1, type: 'image' },
  { id: 2, url: img1, type: 'image' },
  { id: 3, url: img1, type: 'image' },
  { id: 4, url: video1, type: 'video' },
  { id: 5, url: img1, type: 'image' },
  { id: 6, url: video1, type: 'video' },
  { id: 7, url: img1, type: 'image' },
  { id: 8, url: video1, type: 'video' }
])

onMounted(() => {
  initDragSort()
})

const initDragSort = () => {
  nextTick(() => {
    // 选择包含所有可排序项目的容器
    const el = uploadImgItem.value

    // 确保 el 是一个有效的 DOM 元素
    if (el) {
      Sortable.create(el, {
        group: 'shared', // 设置同一组内的元素可以互相排序
        fallbackOnBody: true, // 如果需要的话,可以在 body 上进行拖拽
        swapThreshold: 0.65, // 控制元素交换的阈值
        onEnd: (/** 事件对象 */ evt) => {
          // 获取旧的索引和新索引
          const { oldIndex, newIndex } = evt

          // 交换位置
          const movedItem = imgList.value.splice(oldIndex, 1)[0]
          imgList.value.splice(newIndex, 0, movedItem)
          console.log(imgList.value)
        }
      })
    }
  })
}

具体实现效果:

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值