1. 程式人生 > 其它 >在vue基礎上實現原生拖動事件draggable

在vue基礎上實現原生拖動事件draggable

技術標籤:前端學習經歷vuejavascripthtml前端

上程式碼

  <div class="test-view">
    <div ref="from" class="from">
      <div class="item" draggable @dragstart="itemDragStart" :style="{backgroundColor:item.color}" v-for="item in fromData"
:key="item.name">
{{item.name}}</div> </div> <div class="to" @dragenter="toDragEnter" @dragover="e=>e.preventDefault()" @drop="drop" @dragleave="toDragLeave"> <div class="item" :style="{
backgroundColor:item.color}
"
v-for="item in toData" :key="item.name">
{{item.name}}</div> </div> </div>
export default {
  components: {
  },
  data() {
    return {
      fromData: [
        {
          name: "節點1",
          color: "red"
}, { name: "節點2", color: "yellow" }, { name: "節點3", color: "blue" } ], toData: [], toEle: null } }, methods: { itemDragStart(e) { console.log("元素拖動開始", e); }, drop(e) { console.log("元素釋放", e); // if (!this.toEle) return; // const one = this.fromData.find(x => x.name == e.target.innerText); // this.toData.push(one); }, toDragEnter(e) { console.log("元素拖動進入盒子", e); this.toEle = e; }, toDragLeave(e) { console.log("元素拖動離開盒子", e); this.toEle = null; } }, mounted() { } }
 .test-view {
    width: 100%;
    height: 100%;
    background-color: #1f1d27;
    position: relative;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .from,
    .to {
      width: 200px;
      height: 500px;
      background-color: #464648;
      padding: 10px;
      border-radius: 10px;
      .item {
        width: 100%;
        height: 35px;
        margin: 10px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #010101;
        font-size: 16px;
        font-weight: bold;
        border-radius: 5px;
        user-select: none;
        cursor: pointer;
      }
    }
  }

需要注意的地方

在需要放入的盒子繫結兩個事件
@dragover 和 @drop,後者是放開時候觸發的。但是前面那個是必須要寫,並且要執行e.preventDefault(),否者@drop無法觸發。