拖拽排序,改变原来对象中的orderIndex

用的是vuedraggable,在拖动后@sort方法会返回拖动对象原来的Index和拖动后的Index
在拖动排序后,手动改变原来list对象内的orderIndex

<template>
  <Draggable :list="list" @sort="sort">
    <!--具体需要拖拽排序的内容,这里省略-->
  </Draggable>
</template>
<script>
import Draggable from 'vuedraggable'
export default {
  components: {
    Draggable
  },
  data () {
    return {
      list: [{orderIndex: 1}, {orderIndex: 2}]
    }
  },
  methods: {
    // 排序改变
    sort ({ newIndex, oldIndex }) {
      <!-- 记录拖拽对象的orderIndex-->
      let oldOrder = this.subQuesList[newIndex].orderIndex
      
      <!-- 从拖拽后元素位置开始,赋值上一个元素的orderIndex -->
      let i = newIndex
      while (i !== oldIndex) {
        <!-- 判断是往前拖拽还是往后拖拽 -->
        if (newIndex > oldIndex) {
          this.subQuesList[i].orderIndex = this.subQuesList[i - 1].orderIndex
          i--
        } else {
          this.subQuesList[i].orderIndex = this.subQuesList[i + 1].orderIndex
          i++
        }
      }
      
      <!-- 最后一个元素,赋值一开始记录的拖拽对象的orderIndex -->
      this.subQuesList[oldIndex].orderIndex = oldOrder
    }
  }
}
</script>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容