这篇“Vue.Draggable怎么实现交换位置”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Vue.Draggable怎么实现交换位置”文章吧。
如下图:
c拖拽到a的位置,表现为c插入到a的前面。所以变为了cab。
需求
实现交换而非插入及上图要变成(cba)
实现方式
想要阻止它插入是不可能,我们只能等它插入结束后对我们想要的元素进行操作。比如拿到头和尾部两个索引。交换他们在数组中的位置。需要注意的是,因为拖拽时已经改变数组里面元素的位置了,因此我们需要在拖拽前copy一个和原数组一样的数组。
实现步骤
1、 选择一个适合自己的方法,需要能够获得开始索引和结束索引
end,sort,update都可以
2、深拷贝
copyList(){
this.copyList=this.list.slice(0)
}
3、通过索引来操作copyList数组位置
const item=this.copyList[oldIndex]
this.copyList.splice(oldIndex, 1, this.copyList[newIndex]);
this.copyList.splice(newIndex, 1, item);
4、将copyList赋值给list,并在结尾处获得新的拷贝的copyList
this.list=this.copyList
this.copyList = this.list.slice(0);
全部代码
import draggable from "@/vuedraggable";
let id = 1;
export default {
name: "simple",
display: "Simple",
order: 0,
components: {
draggable,
},
data() {
return {
enabled: true,
list: [{ name: "a" }, { name: "b" }, { name: "c" }],
dragging: false,
index: 0,
copyList: [],
};
},
computed: {
draggingInfo() {
return this.dragging ? "under drag" : "";
},
},
created() {
this.copyList = this.list.slice(0);
},
methods: {
add: function () {
this.list.push({ name: "Juan " + id, id: id++ });
},
replace: function () {
this.list = [{ name: "Edgard", id: id++ }];
},
end({ oldIndex, newIndex }) {
const item = this.copyList[oldIndex];
this.copyList.splice(oldIndex, 1, this.copyList[newIndex]);
this.copyList.splice(newIndex, 1, item);
this.list = this.copyList;
this.copyList = this.list.slice(0);
},
}
};
<draggable
:list="list"
:disabled="!enabled"
class="list-group"
ghost-class="ghost"
:move="checkMove"
@end="end"
@sort="sort"
@update="update"
@start="start"
>
<div class="list-group-item" v-for="element in list" :key="element.name">{{ element.name }}</div>
</draggable>
以上就是关于“Vue.Draggable怎么实现交换位置”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。