vue.draggable实现交换位置,供大家参考,具体内容如下
前言
最近的一个项目接触了到了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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。