在vue基础上实现原生拖动事件draggable

上代码

  <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无法触发。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值