vue项目中原生 API 实现拖拽

效果图
在这里插入图片描述

<template>
  <div style="width: 300px; height: 500px">
    <ul class="list">
      <li v-for="(item, index) in list" :key="item.label">
        <div
          class="flex"
          :draggable="draggable"
          style="display: flex; justify-content: space-between"
          @dragenter="dragenter($event, index)"
          @dragover="dragover($event, index)"
          @dragstart="dragstart(index)"
        >
          <div>{{ item.label }}</div>
          <div class="list-item1">删除</div>
          <span @mousedown="mousedown"  class="list-item"
            >拖动
          </span>
        </div>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          label: "列表1",
          icon: "图标1",
        },
        {
          label: "列表2",
          icon: "图标2",
        },
        {
          label: "列表3",
          icon: "图标3",
        },
        {
          label: "列表4",
          icon: "图标4",
        },
        {
          label: "列表5",
          icon: "图标5",
        },
        {
          label: "列表6",
          icon: "图标6",
        },
      ],
      dragIndex: "",
      enterIndex: "",
      draggable: false,
    };
  },
  computed: {},
  mounted() {
    window.addEventListener("mousedown", (e) => {
      console.log(" ~ " + "e.target.localName" + "---------", e.target.localName);
      if (e.target.localName !== "span") {
        this.draggable = false;
      }
    });

  },
  methods: {
    mousedown() {
      this.draggable = true;
    },

    dragstart(index) {
      this.dragIndex = index;
    },
    dragenter(e, index) {
      this.aa = e.target.localName;
      // console.log(e.target.localName);
      if (e.target.localName === "span") {
        e.preventDefault();
        if (this.dragIndex !== index) {
          const source = this.list[this.dragIndex];
          this.list.splice(this.dragIndex, 1);
          this.list.splice(index, 0, source);
          this.dragIndex = index;
        }
      }
    },
    dragover(e) {
      // console.log(e, index);
      e.preventDefault();
    },
  },
};
</script>
<style scoped>
/* .list {
  list-style: none;

}
.list-item {
  cursor: move;
  width: 200px;
  background: pink;
  border-radius: 4px;
  color: #FFF;
  margin-bottom: 6px;
  height: 50px;
  line-height: 50px;
} */
.list {
  list-style: none;
}
.list-item {
  cursor: pointer;
  /* width: 60px; */
  display: inline-block;
  color: rgb(15, 15, 15);
  line-height: 20px;
}

.list-item1 {
  cursor: pointer;
  /* width: 0px; */
  color: rgb(233, 9, 9);
  line-height: 20px;
}
</style>

在这里插入图片描述
参考文章 http://t.csdn.cn/Qdxh9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值