uniapp横向拖拽排序功能如何实现

在UniApp中如何实现横向拖拽排序功能?例如一个横向滚动的列表,每个项目可以长按拖拽调整顺序。请问有没有现成的插件或组件可以直接使用,或者需要自己实现?具体实现思路是什么?求指教!

2 回复

使用movable-areamovable-view组件实现横向拖拽。

  1. 外层包裹movable-area,设置宽高
  2. 内层多个movable-view,设置direction="horizontal"
  3. 监听change事件获取位置变化
  4. 通过动态调整数组顺序实现排序效果

在 UniApp 中实现横向拖拽排序功能,可以通过以下步骤完成:

实现思路

  1. 使用 movable-viewmovable-area 组件实现拖拽。
  2. 结合 touchstarttouchmovetouchend 事件处理排序逻辑。
  3. 动态更新数据数组,实现排序效果。

示例代码

<template>
  <view class="container">
    <movable-area class="movable-area">
      <movable-view
        v-for="(item, index) in list"
        :key="item.id"
        class="movable-view"
        direction="horizontal"
        :x="item.x"
        @change="onChange($event, index)"
        @touchstart="onTouchStart(index)"
        @touchend="onTouchEnd(index)"
      >
        <view class="item">{{ item.name }}</view>
      </movable-view>
    </movable-area>
  </view>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { id: 1, name: '项目1', x: 0 },
        { id: 2, name: '项目2', x: 120 },
        { id: 3, name: '项目3', x: 240 }
      ],
      startIndex: -1,
      currentX: 0
    };
  },
  methods: {
    onTouchStart(index) {
      this.startIndex = index;
      this.currentX = this.list[index].x;
    },
    onChange(e, index) {
      if (this.startIndex === index) {
        this.list[index].x = e.detail.x;
      }
    },
    onTouchEnd(index) {
      if (this.startIndex !== index) return;
      
      const movedDistance = this.list[index].x - this.currentX;
      if (Math.abs(movedDistance) > 60) { // 移动阈值,调整排序
        const direction = movedDistance > 0 ? 1 : -1;
        const targetIndex = index + direction;
        
        if (targetIndex >= 0 && targetIndex < this.list.length) {
          // 交换数据
          [this.list[index], this.list[targetIndex]] = [this.list[targetIndex], this.list[index]];
          // 重置位置
          this.list.forEach((item, i) => {
            item.x = i * 120;
          });
        } else {
          // 复位
          this.list[index].x = this.currentX;
        }
      } else {
        // 复位
        this.list[index].x = this.currentX;
      }
      this.startIndex = -1;
    }
  }
};
</script>

<style>
.movable-area {
  width: 100%;
  height: 100px;
  background: #f0f0f0;
}
.movable-view {
  width: 100px;
  height: 80px;
  background: #007AFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}
.item {
  text-align: center;
}
</style>

关键点说明

  • movable-area:定义拖拽区域。
  • movable-view:可拖拽的视图,通过 x 属性控制位置。
  • 事件处理
    • touchstart 记录开始拖拽的索引和初始位置。
    • change 实时更新元素位置。
    • touchend 判断移动距离,触发排序或复位。
  • 排序逻辑:根据移动方向交换数据,并重新计算所有元素位置。

优化建议

  • 可添加动画效果提升体验。
  • 根据实际需求调整移动阈值和元素间距。

以上代码实现了基本的横向拖拽排序,可根据项目需求调整样式和交互细节。

回到顶部