uniapp拖动表格
uniapp 实现拖动表格的方法
在 uniapp 中实现表格的拖动功能,可以通过以下几种方式实现:
使用 movable-view 和 movable-area 组件
movable-view 和 movable-area 是 uniapp 提供的可拖动组件,适合实现简单的拖动功能。
<template>
<movable-area style="width: 100%; height: 100vh;">
<movable-view
v-for="(item, index) in tableData"
:key="index"
direction="all"
:x="item.x"
:y="item.y"
@change="onChange(index, $event)"
>
{{ item.text }}
</movable-view>
</movable-area>
</template>
<script>
export default {
data() {
return {
tableData: [
{ text: 'Item 1', x: 0, y: 0 },
{ text: 'Item 2', x: 100, y: 100 },
]
}
},
methods: {
onChange(index, e) {
this.tableData[index].x = e.detail.x
this.tableData[index].y = e.detail.y
}
}
}
</script>
使用第三方库 sortablejs
sortablejs 是一个功能强大的拖拽排序库,可以轻松实现表格行的拖动排序。
-
安装
sortablejs:npm install sortablejs --save -
在页面中使用:
<template> <view> <view id="table"> <view v-for="(item, index) in tableData" :key="item.id" class="table-row" > {{ item.text }} </view> </view> </view> </template>
export default { data() { return { tableData: [ { id: 1, text: 'Row 1' }, { id: 2, text: 'Row 2' }, ] } }, mounted() { const el = document.getElementById('table') new Sortable(el, { animation: 150, onEnd: (evt) => { const { oldIndex, newIndex } = evt const movedItem = this.tableData.splice(oldIndex, 1)[0] this.tableData.splice(newIndex, 0, movedItem) } }) } }
.table-row { padding: 10px; border: 1px solid #eee; margin-bottom: 5px; } ```使用 touch 事件手动实现拖动
通过监听 touchstart、touchmove 和 touchend 事件,可以手动实现拖动效果。
<template>
<view>
<view
v-for="(item, index) in tableData"
:key="index"
class="draggable-item"
@touchstart="handleTouchStart(index, $event)"
@touchmove="handleTouchMove(index, $event)"
@touchend="handleTouchEnd"
:style="{ transform: `translate(${item.x}px, ${item.y}px)` }"
>
{{ item.text }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
tableData: [
{ text: 'Item 1', x: 0, y: 0, isDragging: false },
{ text: 'Item 2', x: 0, y: 50, isDragging: false },
],
startX: 0,
startY: 0
}
},
methods: {
handleTouchStart(index, e) {
this.tableData[index].isDragging = true
this.startX = e.touches[0].clientX - this.tableData[index].x
this.startY = e.touches[0].clientY - this.tableData[index].y
},
handleTouchMove(index, e) {
if (!this.tableData[index].isDragging) return
this.tableData[index].x = e.touches[0].clientX - this.startX
this.tableData[index].y = e.touches[0].clientY - this.startY
},
handleTouchEnd(index) {
this.tableData[index].isDragging = false
}
}
}
</script>
<style>
.draggable-item {
position: absolute;
width: 100px;
height: 40px;
background-color: #f0f0f0;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
}
</style>
注意事项
- 在移动端使用拖动功能时,需注意触摸事件的兼容性。
- 使用
sortablejs时,需确保 DOM 元素已渲染完成后再初始化。 - 拖动性能优化:对于大量数据,建议使用虚拟滚动技术(如
uni-list)减少渲染压力。
以上方法可根据实际需求选择,movable-view 适合简单拖动,sortablejs 适合复杂排序,手动实现则提供最大灵活性。







