在 uni-app 中,你可以使用组件 <drag-left-right /> 来实现左右拖动 div 换位的效果。

  1. 在需要实现左右拖动换位的页面中,导入 <drag-left-right /> 组件:
<template>
  <view class="container">
    <drag-left-right>
      <!-- 需要左右拖动换位的 div -->
      <view class="item">item1</view>
      <view class="item">item2</view>
      <!-- 其他内容 -->
    </drag-left-right>
  </view>
</template>

<script>
import DragLeftRight from '@/components/drag-left-right/drag-left-right.vue';

export default {
  components: {
    DragLeftRight
  }
}
</script>
  1. 在组件内部,使用 v-for 循环渲染需要左右拖动换位的 div 元素。
<template>
  <view class="container">
    <drag-left-right>
      <view class="item" v-for="(item, index) in items" :key="index" ref="items">{{ item }}</view>
    </drag-left-right>
  </view>
</template>

<script>
import DragLeftRight from '@/components/drag-left-right/drag-left-right.vue';

export default {
  data() {
    return {
      items: ['item1', 'item2', 'item3']
    }
  },
  components: {
    DragLeftRight
  }
}
</script>
  1. <drag-left-right /> 组件中,使用 touchstarttouchend 事件监听手指滑动,并在 touchend 事件中调用换位方法。
<template>
  <view class="drag-left-right">
    <view
      class="item"
      v-for="(item, index) in items"
      :key="index"
      ref="items"
      @touchstart="touchStart"
      @touchend="touchEnd"
    >
      {{ item }}
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      items: ['item1', 'item2', 'item3']
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐