vue3中javascript 使用 sortable 实现 table 拖拽排序功能,提供排列顺序,先固定格式查看
时间: 2024-10-12 10:11:26 浏览: 78
在 Vue 3 中,要实现表格的拖拽排序功能,你可以利用 `sortablejs` 这个 JavaScript 库来轻松完成。SortableJS 提供了一套丰富的 API 和组件化设计,可以方便地添加排序功能到各种列表或表格中。
首先,你需要安装 `sortablejs`,可以在项目中通过 npm 或者 yarn 安装:
```bash
npm install sortablejs
# 或者
yarn add sortablejs
```
接下来,在 Vue 组件中引入并设置表格为可排序:
```html
<template>
<table ref="sortTable">
<!-- 表格列和行 -->
<tr v-for="(item, index) in items" :key="index">
<td @dragstart.prevent="dragStart(item, $event)" @drop="drop($event, item)">
{{ item.name }} <!-- 或其他需要排序的数据项 -->
</td>
</tr>
</table>
</template>
<script setup>
import Sortable from 'sortablejs';
const items = ref([]); // 初始化数据
function dragStart(item, event) {
event.dataTransfer.setData('text/plain', item.id); // 传递需要排序的标识
}
function drop(event, draggedItem) {
const targetIndex = event.target.closest('tr').index; // 获取目标行索引
const sortedItems = items.value;
// 使用 sortablejs 的 update 函数处理排序
sortable.update('sortTable', {
onEnd: (e) => {
const newIndex = e.newIndex;
sortedItems.splice(newIndex, 0, draggedItem);
sortedItems.splice(targetIndex, 1); // 移除原位置的元素
items.value = sortedItems; // 更新数据
}
});
}
</script>
```
在这个例子中,我们首先在模板中设置了每个单元格可以触发 `dragstart` 和 `drop` 事件。`dragStart` 函数负责保存拖动的元素标识,`drop` 函数则在松开鼠标时更新列表的排序。
记得初始化 Sortable 对象,并在 `update` 回调中管理排序操作。这样当你拖动表头的行时,它会按照新位置进行调整。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)