vuedraggable是一个vue的拖拽插件,可实现排序拖拽和*拖拽,使用步骤和代码示例如下:
1、安装vuedraggable
npm install vuedraggable
2、页面引入
import draggable from 'vuedraggable';
3、示例:
实现顺序拖拽:
这种是最常规的简单用法。可用于列表拖拽排序等。拖拽后的componentList就是按照顺序排列好的。
<template>
<div class='testPage' ref='testPage'>
<draggable
:list="componentList"
ghost-class="ghost"
chosen-class="chosenClass"
animation="300"
@start="onStart"
@end="onEnd"
class="draggable"
>
<template #item="{ element }">
<div class='item' style='width: 200px; height: 40px; border: 1px solid #EEEEEE;'>
{{element.name}}
</div>
</template>
</draggable>
</div>
</template>
import draggable from 'vuedraggable';
export default {
name: 'wel',
components: {draggable},
data() {
return {
componentList: [
{
id: 1,
name: '测试1'
},
{
id: 2,
name: '测试2'
},
{
id: 3,
name: '测试3'
},
{
id: 4,
name: '测试4'
},
{
id: 5,
name: '测试5'
}
],
offsetX: 0,
offsetY: 0,
pageY: 0,
pageX: 0
};
},
computed: {},
created() {},
methods: {
onStart() {
},
onEnd(e) {
}
},
};
.testPage {
.draggable {
width: 100%;
height: 100%;
position: relative;
}
.item {
background: #FFFFFF;
}
.item:hover {
cursor: move;
}
.ghost {
border: solid 1px rgb(19, 41, 239);
}
.chosenClass {
background-color: #f1f1f1;
}
}
实现随意位置拖拽:
可随意位置拖拽,不用相邻,也不用排序,其实就是在原基础上把所有元素绝对定位,然后动态计算出移动后元素的位置,动态设置top和left值。
<template>
<div class='testPage' ref='testPage'>
<draggable
:list="componentList"
ghost-class="ghost"
chosen-class="chosenClass"
animation="300"
@start="onStart"
@end="onEnd"
class="draggable"
:sort='false'
>
<template #item="{ element }">
<div class='item' style='width: 200px; height: 200px; position: absolute; border: 1px solid #EEEEEE;' @mousedown='mousedownHandle'>
{{element.name}}
</div>
</template>
</draggable>
</div>
</template>
import draggable from 'vuedraggable';
export default {
name: 'wel',
components: {draggable},
data() {
return {
componentList: [
{
id: 1,
name: '测试1'
},
{
id: 2,
name: '测试2'
},
{
id: 3,
name: '测试3'
},
{
id: 4,
name: '测试4'
},
{
id: 5,
name: '测试5'
}
],
offsetX: 0,
offsetY: 0,
pageY: 0,
pageX: 0
};
},
computed: {},
created() {},
methods: {
onStart() {
},
onEnd(e) {
e.item.style.top = e.originalEvent.pageY - this.offsetY - this.pageY + 'px';
e.item.style.left = e.originalEvent.pageX - this.offsetX - this.pageX + 'px';
},
mousedownHandle(e) {
this.offsetX = e.offsetX;
this.offsetY = e.offsetY;
var rectInfo = this.$refs.testPage.getBoundingClientRect();
this.pageX = rectInfo.left;
this.pageY = rectInfo.top;
}
},
};
.testPage {
background: url("@/assets/images/map_bg.png") no-repeat center center !important;
background-size: 100% 100%;
position: relative;
.draggable {
width: 100%;
height: 100%;
position: relative;
}
.item {
background: #FFFFFF;
}
.item:hover {
cursor: move;
}
.ghost {
border: solid 1px rgb(19, 41, 239);
}
.chosenClass {
background-color: #f1f1f1;
}
}