Vue.Draggable交换位置

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue.Draggable交换位置

Landing...   2022-05-28 我要评论

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>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们