效果图
<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