Python后端项目中,如何使用vuedraggable实现前后端分离的拖动保存数据?
vuedraggable 拖动排序及移动对象的代码全部写在 html 文件中的服务端渲染,请问各位前端大神,如何实现拖动保存 /更新数据?后端用的 Python/Django,是服务端渲染,没有使用 json 这种前后端分离的模式进行数据交互哦,非常感谢!
Python后端项目中,如何使用vuedraggable实现前后端分离的拖动保存数据?
4 回复
看描述你的问题等于 = 服务端渲染下前端如何提交数据给后端
核心思路: 前端用 vuedraggable 处理拖动排序,生成新的顺序数组;后端接收这个数组,更新数据库中的排序字段(如 order_index)。
前端 Vue 3 + vuedraggable 示例:
<template>
<div>
<draggable
v-model="items"
item-key="id"
@end="onDragEnd"
>
<template #item="{ element }">
<div class="item">{{ element.name }} (顺序: {{ element.order_index }})</div>
</template>
</draggable>
</div>
</template>
<script setup>
import { ref } from 'vue'
import draggable from 'vuedraggable'
// 初始数据(从后端获取)
const items = ref([
{ id: 1, name: '项目A', order_index: 1 },
{ id: 2, name: '项目B', order_index: 2 },
{ id: 3, name: '项目C', order_index: 3 }
])
// 拖动结束事件
const onDragEnd = async () => {
// 重新计算顺序值(从1开始)
const updatedItems = items.value.map((item, index) => ({
...item,
order_index: index + 1
}))
// 发送到后端
try {
const response = await fetch('/api/update-order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items: updatedItems })
})
if (response.ok) {
console.log('顺序保存成功')
}
} catch (error) {
console.error('保存失败:', error)
}
}
</script>
后端 FastAPI 示例:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
import asyncpg # 异步PostgreSQL驱动
app = FastAPI()
# 数据模型
class ItemUpdate(BaseModel):
id: int
order_index: int
class UpdateRequest(BaseModel):
items: List[ItemUpdate]
# 数据库连接池(示例配置)
DATABASE_URL = "postgresql://user:pass@localhost/dbname"
@app.post("/api/update-order")
async def update_order(request: UpdateRequest):
try:
# 连接数据库
conn = await asyncpg.connect(DATABASE_URL)
# 批量更新顺序
async with conn.transaction():
for item in request.items:
await conn.execute(
"UPDATE items SET order_index = $1 WHERE id = $2",
item.order_index, item.id
)
await conn.close()
return {"message": "顺序更新成功"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
关键点:
- 前端拖动时只改变本地数组顺序,结束时才发送请求
- 后端用事务保证批量更新的一致性
- 数据库表需要
order_index字段存储顺序
一句话建议: 前端传ID和新顺序数组,后端批量更新排序字段。
是的,你知道 vue.js 怎么实现吗
服务端渲染仅仅是服务端生成纯 html,最终的 js 代码依然是在客户机的浏览器执行,没法直接调用你跑在服务器的服务端代码。所以还是要通过接口来调

