亲宝软件园·资讯

展开

js拖拽排序

zhaojiancheng 人气:0

运行环境:vue3.2以上,复制张贴运行即可看效果
效果如下:

<template>
  <div class="container">
    <transition-group name="flip-list">
      <div v-for="item in items" :key="item" draggable="true" class="items" @dragstart="dragstart(item)"
        @dragenter="dragenter(item)" @dragend="dragend">{{item}}</div>
    </transition-group>
  </div>
</template>
 
<script setup>
import { ref } from "vue";
const items = ref([1, 2, 3, 4, 5, 6, 7, 8, 9])
const oldNum = ref(0)
const newNum = ref(0)
// 记录初始信息
const dragenter = (param) => {
  newNum.value = param
}
// 做最终操作
const dragend = () => {
  if(oldNum.value !== newNum.value){
    const oldIndex = items.value.indexOf(oldNum.value)
    const newIndex = items.value.indexOf(newNum.value)
    const newItems = [...items.value]
    // 删除老的节点
    newItems.splice(oldIndex,1)
    // 在列表中目标位置增加新的节点
    newItems.splice(newIndex,0,oldNum.value)
    // items改变transition-group就会起作用
    items.value = [...newItems]
  }
}
// 记录移动过程中信息
const dragstart = (param) => {
  oldNum.value = param;
}
</script>
<style scoped>
.items {
  width: 300px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  background: linear-gradient(45deg, #234, #567);
  color: pink;
}
 
.flip-list-move {
  transition: transform 1s;
}
</style>

加载全部内容

相关教程
猜你喜欢
用户评论