如何在Inertia.js 3的setup方法中获取当前页码(Laravel 10)
在Laravel 10 + Inertia.js 3中无需解析URL获取当前分页页码
不用手动解析window.location字符串,直接利用Laravel和Inertia的内置能力就能轻松拿到当前页码,以下是两种实用方法:
1. 从分页数据Props中直接读取
当你在后端用Laravel分页器返回数据时,分页结果自带current_page字段,Inertia会自动将这个数据传递到前端组件的props中:
后端代码示例
return Inertia::render('YourPageComponent', [ 'dataList' => YourModel::paginate(15), // 按15条每页分页 ]);
前端Vue组件中获取
<script setup> import { defineProps } from 'vue'; const props = defineProps({ dataList: { type: Object, required: true, }, }); // 直接拿到当前页码 const currentPage = props.dataList.current_page; </script>
2. 通过Inertia路由钩子获取查询参数
Inertia已经自动解析了URL的查询参数,借助useRoute钩子可以直接提取page参数:
前端Vue组件示例
<script setup> import { useRoute } from '@inertiajs/vue3'; const route = useRoute(); // 获取页码,无参数时默认设为1 const currentPage = route.query.page ?? 1; </script>
这两种方法都比手动解析URL更可靠,也更符合Laravel + Inertia的开发规范,避免了字符串处理可能带来的错误。
内容的提问来源于stack exchange,提问作者mstdmstd
相关产品推荐
相关产品推荐

