Vue.js/Vuetify结合Django REST Framework服务端分页数据不更新问题
问题描述
我正在开发一个Django API应用,后端用rest_framework.pagination.PageNumberPagination实现分页,接口返回格式如下:
{ "count": 8025, "next": "http://localhost:8000/api/v1/businessunits/?page=2", "previous": null, "results": [] }
为减少大数据量带来的加载延迟,我尝试将分页数据接入Vuetify的v-data-table-server,但切换分页时,虽然options已更新为对应页码,页面渲染的数据却始终是上一页的内容。相关前端代码如下:
data() { return { loading: false, currentPage: 1, search: "", totalBusinessUnits: 0, options: {}, sortBy: [], businessUnits: [], selectedColumn: null, headers: [].... } }, watch: { options: { handler(options) { this.getBusinessUnits(); }, deep: false }, }, getBusinessUnits() { this.loading = true; const { currentPage } = this.options; let pageNumber = currentPage - 1; const url = `${base_url}${bu_urls.get_all}?page=${this.currentPage}`; console.log(currentPage, pageNumber) axios .get(url, header) .then(response => { this.loading = false; this.businessUnits = response.data.results; this.totalBusinessUnits = response.data.count; console.log(this.options) }) .catch((error) => { console.error("Error fetching business units:", error); }); }, created() { this.getBusinessUnits(); // Execute the getBusinessUnits method on component creation }, mounted() { document.title = "Business Units"; this.getBusinessUnits() },
问题原因及修复方案
核心问题
你在getBusinessUnits方法拼接请求URL时,错误使用了this.currentPage而非从options解构出的currentPage,导致每次请求都携带初始的currentPage=1,自然只会返回第一页数据。另外还有两个次要问题:
- 监听
options时未开启deep: true,如果options是嵌套对象,属性变化可能无法触发监听回调 - 定义了
pageNumber变量但未使用,属于冗余代码
修复步骤
- 修正URL页码参数:将URL中的
this.currentPage替换为从options解构出的currentPage - 开启深度监听:将
watch配置中的deep: false改为deep: true,确保options内部属性变化时能触发请求 - 清理冗余代码:删除未使用的
pageNumber变量
修复后的关键代码片段:
watch: { options: { handler(options) { this.getBusinessUnits(); }, deep: true // 改为深度监听 }, }, getBusinessUnits() { this.loading = true; const { currentPage } = this.options; // 移除无用的pageNumber变量 const url = `${base_url}${bu_urls.get_all}?page=${currentPage}`; // 使用options中的currentPage console.log(currentPage) axios .get(url, header) .then(response => { this.loading = false; this.businessUnits = response.data.results; this.totalBusinessUnits = response.data.count; }) .catch((error) => { console.error("Error fetching business units:", error); }); },
额外优化建议
- 可以删除
data中的currentPage变量,直接用options.currentPage管理当前页码,避免变量冗余 created和mounted中重复调用getBusinessUnits会导致初始请求两次,建议只在created中调用一次
内容的提问来源于stack exchange,提问作者Dezz H
相关产品推荐
相关产品推荐

