最近项目迁移vue3 +ts +vite +element-plus 有一个拖拽的小需求接下来给大家操作一下
一、第一步我们要安装sortablejs 依赖
npm install sortablejs --save
或者
yarn add sortablejs --save
二、在我们需要的组件中引入
import Sortable from 'sortablejs'
三、到这里就可以写我们的功能代码了
<template>
<div class="app-container">
<el-table class="tableContent" row-key="id" border :data="list" style="width: 100%">
<el-table-column label="ID" prop="id" width="70px" align="center" />
<el-table-column label="用户名称" prop="username" width="120px" align="center" />
<el-table-column label="真实姓名" prop="name" width="120px" align="center" />
<el-table-column label="所属部门" prop="deptName" align="center" />
<el-table-column label="邮箱" prop="email" width="150px" align="center" />
<el-table-column label="手机号" prop="mobile" width="150px" align="center" />
<el-table-column label="状态" prop="statusDescribe" width="100px" align="center">
<template #default="{ row }">
<el-tag size="small" :type="row.status === 0 ? 'danger' : ''">{{ row.statusDescribe }}</el-tag>
</template>
</el-table-column>
<el-table-column label="创建时间" prop="createdAt" width="160px" align="center" />
<el-table-column label="操作" align="center" fixed="right" width="150px">
<template #default="{ row }">
<el-button v-permission="['sys:user:update']" type="primary" icon="edit" @click="handleUpdate(row)" />
<el-button v-permission="['sys:user:delete']" type="danger" icon="delete" @click="handleDelete(row)" />
</template>
</el-table-column>
</el-table>
</div>
</template>
哥们儿 哥们儿 敲黑板了!!! 这里我们要注意的是 el-table 的row-id 属性这个必需要添加否则无法拖拽
<script lang="ts">
import {
ref,
toRefs,
onMounted,
reactive,
defineComponent
} from 'vue'
import Sortable from 'sortablejs'
import {
getList
} from '@/api/system/user'
export default defineComponent({
name: 'User',
components: {},
setup() {
const state = reactive({
list: [],
total: 0,
listQuery: {
pageNo: 1,
pageSize: 10,
orderByField: 'createdAt',
orderBy: 'desc'
}
})
const getData = async () => {
try {
const data = await getList(state.listQuery)
state.list = data.list
} catch (error: any) {
throw new Error(error)
}
}
const initSort = (className: string) => {
const table = document.querySelector(`.${ className } .el-table__body-wrapper tbody`);
Sortable.create(table, {
group: 'shared',
animation: 150,
easing: 'cubic-bezier(1, 0, 0, 1)',
onStart: () => {
console.log("开始拖动");
},
onEnd: ({
newIndex,
oldIndex
}: any) => {
console.log(`拖动前索引${oldIndex}---拖动后索引${newIndex}`, "结束拖动");
setNodeSort(state.list,oldIndex,newIndex)
},
})
}
const setNodeSort = (data:any, oldIndex:any, newIndex:any) => {
const currRow = data.splice(oldIndex, 1)[0];
data.splice(newIndex, 0, currRow);
}
onMounted(() => {
getData()
initSort('tableContent')
})
return {
...toRefs(state),
onMounted,
getData,
initSort,
setNodeSort
}
}
})
</script>
以上就完成了一个简单的table 的拖拽功能,功能很简单,代码也不复杂,希望对大家能有所帮助,那么最后兄弟姐妹萌,点赞收藏关注,一键三连走一走,蟹蟹兄弟姐妹萌。
|