vue3 拖动元素到另一个元素中,拖动到删除中

59 阅读1分钟

拖动到区域二

image.png

拖动到删除

image.png

<template>
  <div>
    <div class="flex">
      <div class="pl30 pr30">
        <div
          class="b-a-1 line-color-main1 changheand pt10 pb10 pl15 pr15 br10 mt20"
          v-for="item in forList.list"
          :key="item.id"
          :id="item.id"
          draggable="true"
        >
          {{ item.title }}
        </div>
      </div>
      <div class="flex-1">
        <div class="p30 b-a-1 line-color-main2 mt20" id="quyu1">区域1</div>
        <div class="p30 b-a-1 line-color-main2 mt20" id="quyu2">区域2</div>
        <div class="p30 b-a-1 line-color-main2 mt20" id="shanchu">删除</div>
      </div>
    </div>
  </div>
</template>

<script setup >
import { reactive, ref, onMounted } from 'vue'
let forList = reactive({
  list: [
    { title: '设备1', id: 'one' },
    { title: '设备2', id: 'two' },
    { title: '设备3', id: 'three' }
  ]
})

function initBox() {
  // 拖拽
  let drag = document.getElementsByClassName('changheand')
  // 区域1
  let dropArea = document.getElementById('quyu1')
  // 区域2
  let quyu2 = document.getElementById('quyu2')
  // 删除
  let shanchu = document.getElementById('shanchu')
  // 选择区域内的设备元素
  for (let i = 0; i < drag.length; i++) {
    drag[i].ondragstart = (e) => {
      e.dataTransfer.setData('id', e.target.id)
    }
    drag[i].ondragend = (e) => {
      console.log(e, 'dragend----------')
      e.dataTransfer.clearData('id')
    }
  }

  // 区域二的拖动  拖动
  quyu2.ondragover = (event) => {
    event.target.style.borderStyle = 'dashed'
    event.preventDefault()
  }
  quyu2.ondrop = (event) => {
    event.target.style.borderStyle = 'solid'
    const id = event.dataTransfer.getData('id')
    quyu2.appendChild(document.getElementById(id))
  }

  quyu2.addEventListener('dragleave', (event) => {
    event.target.style.borderStyle = 'solid'
  })

  // 拖动到改区域变为可以的样式
  dropArea.addEventListener('dragover', (event) => {
    event.preventDefault()
  })

  // 拖动结束
  dropArea.addEventListener('drop', (event) => {
    const id = event.dataTransfer.getData('id')
    dropArea.appendChild(document.getElementById(id))
  })

  // 删除 的拖动  
  shanchu.ondragover = (event) => {
    event.target.style.borderStyle = 'dashed'
    event.preventDefault()
  }
  shanchu.ondrop = (event) => {
    event.target.style.borderStyle = 'solid'
    const id = event.dataTransfer.getData('id')
    let index = forList.list.findIndex((item) => item.id === id)
    forList.list.splice(index, 1)
  }
}

onMounted(() => {
  initBox()
})
</script>