vue实现列表拖拽排序的示例代码_vue.js

2022年4月27日09:48:28

 本文主要介绍了vue实现列表拖拽排序的示例代码,具体如下:

<template>
  <div class="test_wrapper" @dragover="dragover($event)">
    <transition-group class="transition-wrapper" name="sort">
      <div v-for="(item) in dataList" :key='item.id' class="sort-item"
        :draggable="true"
        @dragstart="dragstart(item)"
        @dragenter="dragenter(item,$event)"
        @dragend="dragend(item,$event)"
        @dragover="dragover($event)"
      >
        {{ item.label }}
      </div>
    </transition-group>
  </div>
</template>
 
<script lang="ts">
  import {Vue, Component, Prop, Watch} from "vue-property-decorator";
  import { addWebsite } from '@/api'
  @Component({
    components: {}
  })
  export default class Test extends Vue {
 
    oldData: any = null; // 开始排序时按住的旧数据
    newData: any = null; // 拖拽过程的数据
 
    // 列表数据
    dataList:any = [
      { id:1,label:'测试一号' },
      { id:2,label:'测试二号' },
      { id:3,label:'测试三号' },
      { id:4,label:'测试四号' },
    ];
 
    dragstart(value: any) {
      this.oldData = value
    }
 
    // 记录移动过程中信息
    dragenter(value: any, e: any) {
      this.newData = value
      e.preventDefault()
    }
 
    // 拖拽最终操作
    dragend(value: any, e: any) {
      if (this.oldData !== this.newData) {
        let oldIndex = this.dataList.indexOf(this.oldData)
        let newIndex = this.dataList.indexOf(this.newData)
        let newItems = [...this.dataList]
        // 删除老的节点
        newItems.splice(oldIndex, 1)
        // 在列表中目标位置增加新的节点
        newItems.splice(newIndex, 0, this.oldData)
        this.dataList = [...newItems]
      }
    }
 
 
    // 拖动事件(主要是为了拖动时鼠标光标不变为禁止)
    dragover(e: any) {
      e.preventDefault()
    }
 
 
  };
</script>
<style>
.sort-move {
  transition: transform 0.3s;
}
</style>
  • 作者:最爱松露巧克力  
  • 原文链接:https://blog.csdn.net/weixin_36617251/article/details/123996141
    更新时间:2022年4月27日09:48:28 ,共 1275 字。