本文实例为大家分享了vue实现div拖拽互换位置的具体代码,供大家参考,具体内容如下
template模板
<transition-group tag=\"div\" class=\"container\">
<div class=\"item\" v-for=\"(item,index) in items\" :key=\"item.key\" :style=\"{background:item.color,width:\'80px\',height:\'80px\'}\"
draggable=\"true\"
@dragstart=\"handleDragStart($event, item)\"
@dragover.prevent=\"handleDragOver($event, item)\"
@dragenter=\"handleDragEnter($event, item)\"
@dragend=\"handleDragEnd($event, item)\" >
</div>
</transition-group>
:
< >
export default {
name: \'Toolbar\',
data () {
return {
items: [
{ key: 1, color: \'#ffebcc\'},
{ key: 2, color: \'#ffb86c\'},
{ key: 3, color: \'#f01b2d\'}
],
dragging: null
}
},
methods:{
handleDragStart(e,item){
this.dragging = item;
},
handleDragEnd(e,item){
this.dragging = null
},
//首先把div变成可以放置的元素,即重写dragenter/dragover
handleDragOver(e) {
e.dataTransfer.dropEffect = \'move\'// e.dataTransfer.dropEffect=\"move\";//在dragenter中针对放置目标来设置!
},
handleDragEnter(e,item){
e.dataTransfer.effectAllowed = \"move\"//为需要移动的元素设置dragstart事件
if(item === this.dragging){
return
}
const newItems = [...this.items]
console.log(newItems)
const src = newItems.indexOf(this.dragging)
const dst = newItems.indexOf(item)
newItems.splice(dst, 0, ...newItems.splice(src, 1))
this.items = newItems
}
}
}
</ >
<style scoped>
.container{
width: 80px;
height: 300px;
position: absolute;
left: 0;
display:flex;
flex-direction: column;
padding: 0;
}
.item {
margin-top: 10px;
transition: all linear .3s
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
继续阅读与本文标签相同的文章
上一篇 :
一步步教你理解LSTM
下一篇 :
vue拖拽组件使用方法详解
-
虚拟主机有什么优、缺点?
2026-05-19栏目: 教程
-
服务注册
2026-05-19栏目: 教程
-
服务器被攻击 如何查找漏洞以及攻击手法
2026-05-19栏目: 教程
-
Spring Cloud Zuul的动态路由怎样做?集成Nacos实现很简单
2026-05-19栏目: 教程
-
springboot自动配置原理
2026-05-19栏目: 教程
