You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 05:22:04