Skip to content

引入组件 ​

局部引入

ts
// parent.vue
const FDrag = defineAsyncComponent(() => import('@/components/formaui/f-drag/f-drag.vue'))

基础用法 ​

长按格子进行拖拽排序。items 为数据源,columns 为列数(默认 3)。

html
<f-drag
  :items="items"
  :scroll-top="scrollTop"
  :item-height="itemHeight"
  :columns="columns"
  @change="onChange"
  @sort-end="onSortEnd">
  <template #default="{ entity, height, fixed }">
    <view :style="{ height: height + 'rpx', background: entity.color }">
      {{ entity.title }}
      <text v-if="fixed">固定</text>
    </view>
  </template>
</f-drag>
ts
import { ref } from 'vue'
import type { FDragItem } from '@/components/formaui/f-drag/types'

const itemHeight = ref(210)
const scrollTop = ref(0)
const columns = ref(3)
const items = ref<FDragItem[]>([])

onPageScroll((e) => {
  scrollTop.value = e.scrollTop
})

onLoad(() => {
  const list: FDragItem[] = []
  for (let i = 0; i < 18; i++) {
    list.push({ id: i + 1, title: `${i + 1}`, color: '#5B8FF9', fixed: i === 4 })
  }
  items.value = list
})

const onSortEnd = (detail: { items: FDragItem[] }) => {
  items.value = detail.items
}

const onChange = (detail: { items: FDragItem[] }) => {
  console.log(detail.items)
}

columns 属性:列数,配合 itemHeight 调整格子高度

列数为 3 / 4 / 5 时,演示页分别使用 210 / 160 / 120(单位 rpx)。

fixed 字段:写在 items 单项上,值为 true 时该项不可拖拽、不可换位

ts
{ id: 5, title: '5', fixed: true }

isEdit 属性:为 true 时才可拖拽(默认 true)

默认关闭编辑,用开关控制是否可长按拖拽;单列列表常配合右侧把手样式。

html
<view>
  edit:
  <f-switch :checked="isEdit" @change="(val) => (isEdit = val)" />
</view>
<f-drag
  :items="listItems"
  :columns="1"
  :item-height="100"
  :scroll-top="scrollTop"
  :is-edit="isEdit"
  @sort-end="onListSortEnd">
  <template #default="{ entity, height }">
    <view class="cell" :style="{ height: height + 'rpx' }">
      <text>{{ entity.name }}</text>
      <view class="handle"><!-- 三条横线把手 --></view>
    </view>
  </template>
</f-drag>
ts
const isEdit = ref(false)
const listItems = ref([
  { id: 1, name: '内衣配饰' },
  { id: 2, name: '箱包手袋' },
  { id: 3, name: '美妆护肤' },
  { id: 4, name: '个人清洁' },
  { id: 5, name: '钟表珠宝' },
  { id: 6, name: '电脑办公' },
  { id: 7, name: '食品饮酒' },
  { id: 8, name: '运动户外' }
])

const onListSortEnd = (detail: { items: FDragItem[] }) => {
  listItems.value = detail.items
}

scrollTop / topSize / bottomSize:页面滚动与顶部、底部占用高度,用于拖到边缘时自动滚屏

异步拿到数据后可调用组件 init() 重新计算位置。

插槽 ​

名称说明
default格子内容;作用域参数 entity(业务数据)、fixed、index、height(rpx 数值)、isEdit

属性 ​

名称类型说明默认值
itemsFDragItem[]数据源;约定字段 fixed 表示不可拖拽、不可换位[]
columnsnumber列数3
topSizenumber顶部占用高度0
bottomSizenumber底部占用高度0
itemHeightnumber每项高度,用于计算容器高度,单位 rpx0
scrollTopnumber页面滚动距离0
isEditboolean为 true 时才可拖拽true

事件 ​

事件名说明回调参数
sortEnd拖拽结束时{ items: 排序后的数据 }
change排序发生变化时{ items: 排序后的数据 }
itemClick点击格子(非拖拽时){ key, data, extra }

方法 ​

方法名说明传入参数
init重新初始化(异步数据后)-