一个列表 通过拖拽 改变她的顺序
关键:draggable=“true” 可以拖拽
@dragstart=“” 开始拖拽
@drop=“”
@dragover=‘’
<template>
<div>
<li class="li_row" v-for="(item,index) in linkData " :key="index" draggable="true"
@dragstart="dragstart($event,index)" @drop="drop($event,index)" @dragover='dragover($event)'>
<div class="li_item title">{{item.name}}</div>
</li>
</div>
</template>
<script>
export default {
data() {
return {
linkData: [
{name:'百度',url:'wwww.baidu.com',description:'baidu'},
{name:'腾讯网',url:'wwww.qq.com',description:'tencent'},
{name:'新浪微博',url:'https://www.weibo.com/',description:'weibo'},
{name:'今日头条',url:'https://www.toutiao.com/',description:'bytedance'},
{name:'哔哩哔哩',url:'https://www.bilibili.com/',description:'bilibili'}
]
}
},
methods: {
dragstart(e, index) {
e.dataTransfer.setData('index', index);
},
drop(event, index) {
event.preventDefault();
let startIndex = parseInt(event.dataTransfer.getData('index')); // 数据原本的index
let currentIndex = parseInt(index);// 数据现在的index
console.log("start", startIndex);
console.log("drop", currentIndex);
if (startIndex - currentIndex > 0) {
console.log("要拖拽的元素的索引 大于 当前位置的元素的索引");
this.linkData.splice(currentIndex, 0, this.linkData[startIndex]);
console.log("删除" + startIndex + 1);
this.linkData.splice(startIndex + 1, 1)
} else if (startIndex - currentIndex < 0) {
console.log("要拖拽的元素的索引 小于 当前位置的元素的索引");
this.linkData.splice(currentIndex + 1, 0, this.linkData[startIndex]);
this.linkData.splice(startIndex, 1)
} else {
console.log("什么也不用做");
}
},
// 拖动事件(主要是为了拖动时鼠标光标不变为禁止)
dragover(e) {
e.preventDefault()
},
},
}
</script>
<style lang="scss" scoped>
</style>
参考链接
https://blog.csdn.net/azuretodd/article/details/109973228