Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

当用户从一个页面导航到另一个页面时,SvelteKit 会调用你的 load 函数,但前提是它认为某些内容已发生更改。

¥When the user navigates from one page to another, SvelteKit calls your load functions, but only if it thinks something has changed.

在此示例中,在时区之间导航会导致 src/routes/[...timezone]/+page.js 中的 load 函数重新运行,因为 params.timezone 无效。但 src/routes/+layout.js 中的 load 函数不会重新运行,因为就 SvelteKit 而言,它并没有因导航而失效。

¥In this example, navigating between timezones causes the load function in src/routes/[...timezone]/+page.js to re-run because params.timezone is invalid. But the load function in src/routes/+layout.js does not re-run, because as far as SvelteKit is concerned it wasn’t invalidated by the navigation.

我们可以通过使用 invalidate(...) 函数手动使其无效来解决这个问题,该函数接受一个 URL 并重新运行任何依赖于它的 load 函数。因为 src/routes/+layout.js 中的 load 函数调用 fetch('/api/now'),所以它依赖于 /api/now

¥We can fix that by manually invalidating it using the invalidate(...) function, which takes a URL and re-runs any load functions that depend on it. Because the load function in src/routes/+layout.js calls fetch('/api/now'), it depends on /api/now.

src/routes/[...timezone]/+page.svelte 中,添加每秒调用一次 invalidate('/api/now')onMount 回调:

¥In src/routes/[...timezone]/+page.svelte, add an onMount callback that calls invalidate('/api/now') once a second:

src/routes/[...timezone]/+page
<script>
	import { onMount } from 'svelte';
	import { invalidate } from '$app/navigation';

	let { data } = $props();

	onMount(() => {
		const interval = setInterval(() => {
			invalidate('/api/now');
		}, 1000);

		return () => {
			clearInterval(interval);
		};
	});
</script>

<h1>
	{new Intl.DateTimeFormat([], {
		timeStyle: 'full',
		timeZone: data.timezone
	}).format(new Date(data.now))}
</h1>
<script lang="ts">
	import { onMount } from 'svelte';
	import { invalidate } from '$app/navigation';

	let { data } = $props();

	onMount(() => {
		const interval = setInterval(() => {
			invalidate('/api/now');
		}, 1000);

		return () => {
			clearInterval(interval);
		};
	});
</script>

<h1>
	{new Intl.DateTimeFormat([], {
		timeStyle: 'full',
		timeZone: data.timezone
	}).format(new Date(data.now))}
</h1>

你还可以将函数传递给 invalidate,以防你想要根据模式而不是特定 URL 使其无效

¥[!NOTE] You can also pass a function to invalidate, in case you want to invalidate based on a pattern and not specific URLs

1