VUE3 列表拖拽排序(简单)

<template>
  <div class="main">
    <div class="item" v-for="item in dataList" :key="item" draggable="true"  @dragstart="dragstart(item)" @dragenter="dragenter(item)"
        @dragend="dragend(item)">{{item}}</div>
  </div>
</template>
<script lang="ts" setup>
  import {ref} from 'vue'
  const dataList=ref<string[]>(['第一条数据','第二条数据','第三条数据','第四条数据','第五条数据']);
  const clickVal=ref<string>();
  const moveVal=ref<string>();
  const endVal=ref<string>();
  const dragstart=(item:string):void=>{
    clickVal.value=item
  }
  const dragenter=(item:string):void=>{
    moveVal.value=item
  }
  const dragend=(item:string):void=>{
    endVal.value=item;
    let index=dataList.value.indexOf(item)     //移动元素的当前位置
    let moveObj=moveVal.value ? moveVal.value :''
    let addIndex=dataList.value.indexOf(moveObj)     //要移动后的位置
    dataList.value.splice(index,1)
    dataList.value.splice(addIndex,0,item)
  }
</script>
<style lang="scss" scoped>
  .main{
    margin-left: 600px;
    margin-top: 200px;
    display: flex;
    .item{
      cursor: pointer;
      margin-bottom: 10px;
      width: 300px;
      text-align: center;
      height: 60px;
      line-height: 60px;
      background-color: cadetblue;
      color: #fff;
      margin-left: 50px;
    }
  }
</style>

  

posted @ 2022-03-04 15:12  伴月阁  阅读(2886)  评论(0编辑  收藏  举报