千家信息网

Vue.Draggable怎么实现交换位置

发表于:2025-02-05 作者:千家信息网编辑
千家信息网最后更新 2025年02月05日,这篇"Vue.Draggable怎么实现交换位置"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来
千家信息网最后更新 2025年02月05日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.copyListthis.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);    },  }};
  
{{ element.name }}

以上就是关于"Vue.Draggable怎么实现交换位置"这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注行业资讯频道。

0