vue-draggable-plus 拖拽组件使用

447 阅读1分钟

1、拖拽图片

2、判断图片数量之后禁止拖拽

<template>
  <el-row class="row-bg" justify="space-evenly">
    <el-col :span="6">
      <el-card>

        <div class="demo-image">
          <VueDraggable :disabled="isDisabled" v-model="list1" :animation="150"
            :group="{ name: 'people', pull: 'clone', put: false }" :sort="false"
            class="flex flex-col gap-2 p-4 w-300px bg-gray-500/5 rounded">
            <div v-for="item in list1" :key="item.id" class="cursor-move h-50px bg-gray-500/5 rounded p-3">

              <el-image style="width: 100px; height: 100px" :src="item.url" fit="cover" />

            </div>
          </VueDraggable>
        </div>

      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <VueDraggable v-model="list2" :animation="150" group="people"
          class="demo-image  flex flex-col gap-2 p-4 w-300px m-auto bg-gray-500/5 rounded overflow-auto"
          :onAdd="hasMessage">
          <div v-for="item in list2" :key="item.id" class="cursor-move h-50px bg-gray-500/5 rounded p-3">
            <el-image style="width: 100px; height: 100px" :src="item.url" fit="cover" />
          </div>
        </VueDraggable>
      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>

import { ref } from 'vue'
import { VueDraggable } from 'vue-draggable-plus'
import { ElMessage } from 'element-plus'

const isDisabled = ref(false)
// 要拖拽的图片的地址
const list1 = ref([
  {
    name: '图片1',
    url: "https://th.bing.com/th/id/R.98415963b412fccea2d8c4e2b3f695e8?rik=HdwmF8f2XbTwUQ&riu=http%3a%2f%2fi1.hdslb.com%2fbfs%2farchive%2f25359e94f3481702ce699cc867b236c9d056adbc.jpg&ehk=aFN1%2f0CPFS8Bsm7lcpdWzXbRVVRniH9WE9GQ3nVnTNc%3d&risl=&pid=ImgRaw&r=0",
    id: '1'
  },
  {
    name: '图片2',
    url: "https://puui.qpic.cn/vpic_cover/h3345zrkd0f/h3345zrkd0f_hz.jpg/1280",
    id: '2'
  },
  {
    name: '图片3',
    url: "https://puui.qpic.cn/vpic_cover/j3505kdeuyl/j3505kdeuyl_1678095683_hz.jpg/1280",
    id: '3'
  },
  {
    name: '图片4',
    url: "https://p0.itc.cn/q_70/images03/20220911/7ee51ce1d6f54f9e9f8e6e01e2974b24.jpeg",
    id: '4'
  },
])
const list2 = ref(
  [
  ]
)

//元素从一个列表拖拽到另一个列表时触发
function hasMessage() {
  const len = list2.value.length
  if (len > 3) {
    isDisabled.value = true
    ElMessage({
      showClose: true,
      message: '已经四张图片了',
      type: 'warning',
    })
  }

}

</script>

<style>
html,
body {
  width: 100%;
}

@media screen and (min-width: 1024px) {
  #app {
    width: 100%;
    height: 100%;
    display: block;
    max-width: 100%;
    /* 将 max-width 设置为 0,取消其作用 */
  }
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
  text-align: center;
}

.demo-image {
  height: 50vh;
}
</style>