在 load
函数内调用 fetch(url)
会将 url
注册为依赖。有时使用 fetch
并不合适,在这种情况下,你可以使用 depends(url)
函数手动指定依赖。
¥Calling fetch(url)
inside a load
function registers url
as a dependency. Sometimes it’s not appropriate to use fetch
, in which case you can specify a dependency manually with the depends(url)
function.
由于任何以 [a-z]+:
模式开头的字符串都是有效的 URL,我们可以创建自定义无效键,如 data:now
。
¥Since any string that begins with an [a-z]+:
pattern is a valid URL, we can create custom invalidation keys like data:now
.
更新 src/routes/+layout.js
以直接返回值而不是进行 fetch
调用,并添加 depends
:
¥Update src/routes/+layout.js
to return a value directly rather than making a fetch
call, and add the depends
:
export async function load({ depends }) {
depends('data:now');
return {
now: Date.now()
};
}
现在,更新 src/routes/[...timezone]/+page.svelte
中的 invalidate
调用:
¥Now, update the invalidate
call in src/routes/[...timezone]/+page.svelte
:
<script>
import { onMount } from 'svelte';
import { invalidate } from '$app/navigation';
let { data } = $props();
onMount(() => {
const interval = setInterval(() => {
invalidate('data:now');
}, 1000);
return () => {
clearInterval(interval);
};
});
</script>
<script lang="ts">
import { onMount } from 'svelte';
import { invalidate } from '$app/navigation';
let { data } = $props();
onMount(() => {
const interval = setInterval(() => {
invalidate('data:now');
}, 1000);
return () => {
clearInterval(interval);
};
});
</script>