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

Inertia实现无限滚动:应调用API路由还是Web路由?

Inertia实现无限滚动:要不要用API路由?

完全没必要单独写API路由,直接复用Web路由或者在现有控制器里扩展逻辑就够了,Inertia本身就适配这种前后端交互场景。

具体实现步骤:

  • 前端用Intersection Observer(比监听滚动事件更高效)监听列表底部的加载触发元素,当它进入视口时,调用Inertia的get方法,带上当前最后一条帖子的游标(cursor)参数。
  • 后端可以在原控制器里加个loadMore方法处理加载请求:
public function loadMore(Request $request)
{
    $posts = Post::cursorPaginate(20, ['*'], 'cursor', $request->cursor);
    return response()->json($posts);
}
  • 或者直接复用原index方法,判断是Inertia的AJAX请求时,只返回分页数据:
public function index(Request $request)
{
    $posts = Post::cursorPaginate(20, ['*'], 'cursor', $request->cursor);
    
    if ($request->header('X-Inertia')) {
        return response()->json(['posts' => $posts]);
    }
    
    return Inertia::render('Posts/Index', ['posts' => $posts]);
}
  • 前端拿到新数据后,把它合并到现有帖子数组里,就能实现无限滚动加载的效果。

为什么不用API路由?

Inertia的设计初衷就是让你用Web路由搞定前后端交互,它自带CSRF保护,而且如果你的Web路由已经配置了认证中间件,复用起来完全不用额外处理API的认证逻辑,省心很多。当然如果项目有明确的API分层需求,也可以写API路由,但真的没必要多这一步。

内容的提问来源于stack exchange,提问作者panthro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:27:05