vue-grid-layout組件用vue3寫外部元素拖入功能

<template>
    <div>
        <div>
            <div class="layoutJSON">
                Displayed as <code>[x, y, w, h]</code>:
                <div class="columns">
                    <div class="layoutItem" v-for="item in layout">
                        <b>{{ item.i }}</b>: [{{ item.x }}, {{ item.y }}, {{ item.w }}, {{ item.h }}]
                    </div>
                </div>
            </div>
        </div>
        <br/>
        <div @drag="drag" @dragend="dragend" class="droppable-element" draggable="true"
             unselectable="on">Droppable Element (Drag me!)</div>
        <div id="content">
            <grid-layout ref="gridlayout" :layout.sync="layout"
                         :col-num="12"
                         :row-height="30"
                         :is-draggable="true"
                         :is-resizable="true"
                         :vertical-compact="true"
                         :use-css-transforms="true"
            >
                <grid-item :key="item.i" v-for="item in layout"
                           :x="item.x"
                           :y="item.y"
                           :w="item.w"
                           :h="item.h"
                           :i="item.i"
                >
                    <span class="text">{{ item.i }}</span>
                </grid-item>
            </grid-layout>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, unref, getCurrentInstance, defineExpose } from 'vue'

const ctx = getCurrentInstance().ctx
let mouseXY = { x: null, y: null }
let DragPos = { x: null, y: null, w: 1, h: 1, i: null }
let colNum = 10
const gridlayout = ref(null)
const gridItemRefs = ref([])
const getGridItemRef = (el, index) => {
  if (el) {
    gridItemRefs.value[index] = el
  }
}

const layout = ref([
  { x: 0, y: 0, w: 10, h: 1, i: '0' },
  { x: 0, y: 0, w: 10, h: 2, i: '1' },
  { x: 0, y: 0, w: 2, h: 3, i: '2' },
  { x: 0, y: 0, w: 2, h: 4, i: '3' },
  { x: 0, y: 0, w: 2, h: 5, i: '4' },
  { x: 0, y: 0, w: 2, h: 6, i: '5' },
])

onMounted(() => {
  document.addEventListener(
    'dragover',
    function (e) {
      mouseXY.x = e.clientX
      mouseXY.y = e.clientY
    },
    false,
  )
})

function removeItem(val) {
  const layoutUnref = unref(layout)
  const index = layoutUnref.map((item) => item.i).indexOf(val)
  this.layout.splice(index, 1)
}

function clickGridItem(item) {
  console.log(item)
}

function drag() {
  const layoutUnref = unref(layout)
  let parentRect = document.getElementById('content').getBoundingClientRect()
  let mouseInGrid = false
  if (
    mouseXY.x > parentRect.left &&
    mouseXY.x < parentRect.right &&
    mouseXY.y > parentRect.top &&
    mouseXY.y < parentRect.bottom
  ) {
    mouseInGrid = true
  }
  if (mouseInGrid === true && layoutUnref.findIndex((item) => item.i === 'drop') === -1) {
    layoutUnref.push({
      x: (layoutUnref.length * 2) % (colNum || 12),
      y: layoutUnref.length + (colNum || 12), // puts it at the bottom
      w: 1,
      h: 1,
      i: 'drop',
    })
  }
  let index = layoutUnref.findIndex((item) => item.i === 'drop')
  if (index !== -1) {
    try {
      gridItemRefs.value[layoutUnref.length].style.display = 'none'
    } catch {}
    let el = gridItemRefs.value[index]

    if (mouseInGrid === true && el) {
      el.dragging = { top: mouseXY.y - parentRect.top, left: mouseXY.x - parentRect.left }

      let new_pos = el.calcXY(mouseXY.y - parentRect.top, mouseXY.x - parentRect.left)
      gridlayout.value.dragEvent('dragstart', 'drop', new_pos.x, new_pos.y, 1, 1)
      DragPos.i = String(index)
      DragPos.x = layoutUnref[index].x
      DragPos.y = layoutUnref[index].y
    }
    if (mouseInGrid === false) {
      gridlayout.value.dragEvent('dragend', 'drop', 1, 1, 1, 1)
      layout.value = layoutUnref.filter((obj) => obj.i !== 'drop')
    }
  }
}
function dragend() {
  const layoutUnref = unref(layout)
  let parentRect = document.getElementById('content').getBoundingClientRect()
  let mouseInGrid = false
  if (
    mouseXY.x > parentRect.left &&
    mouseXY.x < parentRect.right &&
    mouseXY.y > parentRect.top &&
    mouseXY.y < parentRect.bottom
  ) {
    mouseInGrid = true
  }
  if (mouseInGrid === true) {
    gridlayout.value.dragEvent('dragend', 'drop', DragPos.x, DragPos.y, 1, 1)
    layout.value = layoutUnref.filter((obj) => obj.i !== 'drop')

    layout.value.push({
      x: DragPos.x,
      y: DragPos.y,
      w: componentInfo?.w ?? 1,
      h: componentInfo?.h ?? 1,
      i: DragPos.i,
    })
    console.log(layout.value)
    // gridlayout.value.dragEvent('dragend', DragPos.i, DragPos.x, DragPos.y, 1, 1)
    // try {
    //   gridItemRefs.value[layoutUnref.length].style.display = 'block'
    // } catch {}
  }
}

defineExpose({
  drag,
  dragend,
})
</script>

<style scoped>

.droppable-element {
    width: 150px;
    text-align: center;
    background: #fdd;
    border: 1px solid black;
    margin: 10px 0;
    padding: 10px;
}


.vue-grid-layout {
    background: #eee;
}

.vue-grid-item:not(.vue-grid-placeholder) {
    background: #ccc;
    border: 1px solid black;
}

.vue-grid-item .resizing {
    opacity: 0.9;
}

.vue-grid-item .static {
    background: #cce;
}

.vue-grid-item .text {
    font-size: 24px;
    text-align: center;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    height: 100%;
    width: 100%;
}

.vue-grid-item .no-drag {
    height: 100%;
    width: 100%;
}

.vue-grid-item .minMax {
    font-size: 12px;
}

.vue-grid-item .add {
    cursor: pointer;
}

.vue-draggable-handle {
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    left: 0;
    background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><circle cx='5' cy='5' r='5' fill='#999999'/></svg>") no-repeat;
    background-position: bottom right;
    padding: 0 8px 8px 0;
    background-repeat: no-repeat;
    background-origin: content-box;
    box-sizing: border-box;
    cursor: pointer;
}

.layoutJSON {
    background: #ddd;
    border: 1px solid black;
    margin-top: 10px;
    padding: 10px;
}

.layoutJSON {
    background: #ddd;
    border: 1px solid black;
    margin-top: 10px;
    padding: 10px;
}

.columns {
    -moz-columns: 120px;
    -webkit-columns: 120px;
    columns: 120px;
}
</style>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末烹吵,一起剝皮案震驚了整個濱河市碉熄,隨后出現(xiàn)的幾起案子肋拔,更是在濱河造成了極大的恐慌锈津,老刑警劉巖凉蜂,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異跃惫,居然都是意外死亡叮叹,警方通過查閱死者的電腦和手機爆存,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來先较,“玉大人,你說我怎么就攤上這事闲勺≡兀” “怎么了菜循?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長癌幕。 經(jīng)常有香客問我衙耕,道長勺远,這世上最難降的妖魔是什么橙喘? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任胶逢,我火速辦了婚禮,結(jié)果婚禮上初坠,老公的妹妹穿的比我還像新娘。我一直安慰自己碟刺,他們只是感情好比搭,可當我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著身诺,像睡著了一般。 火紅的嫁衣襯著肌膚如雪霉赡。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天穴亏,我揣著相機與錄音,去河邊找鬼嗓化。 笑死棠涮,一個胖子當著我的面吹牛刺覆,可吹牛的內(nèi)容都是我干的严肪。 我是一名探鬼主播谦屑,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼氢橙!你這毒婦竟也來了酝枢?” 一聲冷哼從身側(cè)響起悍手,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎坦康,沒想到半個月后竣付,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體涝焙,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡孕暇,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年仑撞,在試婚紗的時候發(fā)現(xiàn)自己被綠了妖滔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片隧哮。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡座舍,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出曲秉,到底是詐尸還是另有隱情采蚀,我是刑警寧澤,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布榆鼠,位于F島的核電站,受9級特大地震影響妆够,放射性物質(zhì)發(fā)生泄漏识啦。R本人自食惡果不足惜神妹,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鸵荠。 院中可真熱鬧冕茅,春花似錦腰鬼、人聲如沸嵌赠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽彼硫。三九已至炊豪,卻和暖如春拧篮,著一層夾襖步出監(jiān)牢的瞬間词渤,已是汗流浹背串绩。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工缺虐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留礁凡,地道東北人高氮。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓顷牌,卻偏偏與公主長得像剪芍,于是被迫代替她去往敵國和親窟蓝。 傳聞我的和親對象是個殘疾皇子罪裹,可洞房花燭夜當晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容