vue 实现循环div拖拽变换位置
程序员文章站
2022-07-14 16:26:22
...
效果图(两张图看效果吧)
首先安装插件 vue-class-component 和 vue-property-decorator
npm install --save vue-class-component
npm install --save vue-property-decorator
完整代码 (可直接复制运行看效果)
<template>
<div class="test_wrapper" @dragover="dragover($event)">
<transition-group class="transition-wrapper" name="sort">
<div v-for="(item) in dataList" :key='item.id' class="module"
:draggable="true"
@dragstart="dragstart(item)"
@dragenter="dragenter(item,$event)"
@dragend="dragend(item,$event)"
@dragover="dragover($event)"
>
{{ item.label }}
</div>
</transition-group>
</div>
</template>
<script>
import {Vue, Component, Prop, Watch} from "vue-property-decorator"
export default {
data(){
return{
oldData:null,
newData:null,
dataList:[
{ id:1,label:'拖曳一' },
{ id:2,label:'拖曳二' },
{ id:3,label:'拖曳三' },
{ id:4,label:'拖曳四' },
{ id:5,label:'拖曳五' },
]
}
},
methods:{
dragstart(val){
this.oldData = val
},
// 拖曳过程
dragenter(value, e) {
this.newData = value
e.preventDefault()
},
// 拖拽结束
dragend(value, e) {
if (this.oldData !== this.newData) {
let oldIndex = this.dataList.indexOf(this.oldData)
let newIndex = this.dataList.indexOf(this.newData)
let newItems = [...this.dataList]
// 删除老的节点
newItems.splice(oldIndex, 1)
// 在列表中目标位置增加新的节点
newItems.splice(newIndex, 0, this.oldData)
this.dataList = [...newItems]
console.log(this.dataList)
}
},
// 拖动事件
dragover(e) {
e.preventDefault()
}
}
}
</script>
<style scoped>
.sort-move {
transition: transform 0.2s;
}
.module{
width: 100px;
text-align: center;
height: 30px;
line-height: 30px;
display: inline-block;
border-radius: 5px;
margin: 0 20px;
background: #1296DB;
color: #fff;
}
</style>