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

如何让SvelteKit中LayoutServerLoad在每次导航时触发?

让+layout.server.ts的load函数每次导航都执行

SvelteKit默认在客户端通过锚点导航时,会复用服务器端加载的布局数据,不会重新调用+layout.server.ts中的load函数,只有页面刷新(如F5)时才会触发。要实现每次导航都执行该函数,可通过以下两种方法:

方法1:禁用结果缓存

直接在+layout.server.ts中配置cache: 'no-store',强制每次请求(包括客户端导航时的请求)都执行load函数:

import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ cookies }) => {
    console.log("running layout on server");
    // 在此添加你的JWT验证/刷新逻辑
};

// 禁用缓存,确保每次导航都触发服务器端load
export const config = {
    cache: 'no-store'
};

方法2:依赖标记+导航时触发失效

如果需要更精准的控制(避免全局禁用缓存),可以通过依赖标记结合客户端导航钩子实现:

  1. 在+layout.server.ts中用depends定义一个自定义依赖键:
import type { LayoutServerLoad } from './$types';
import { depends } from '$app/server';

export const load: LayoutServerLoad = async ({ cookies }) => {
    depends('jwt:validation');
    console.log("running layout on server");
    // JWT验证/刷新逻辑
};
  1. 在+layout.ts中监听导航事件,每次导航前触发该依赖的失效,从而重新执行服务器端的load函数:
import { invalidate, beforeNavigate } from '$app/navigation';

beforeNavigate(() => {
    // 触发依赖失效,强制重新加载服务器端布局数据
    invalidate('jwt:validation');
});

export const load: LayoutServerLoad = async () => {
    // 客户端侧布局加载逻辑(可选)
};

两种方法对比

  • 方法1:实现简单,无需额外客户端代码,但会增加服务器请求量,适合逻辑轻量化的场景。
  • 方法2:更灵活,仅在指定依赖失效时重新执行load函数,性能更优,适合需要精细控制的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 14:24:58