在 上一节关于加载 中,我们使用 +page.server.js
和 +layout.server.js
文件从服务器加载数据。如果你需要执行诸如直接从数据库获取数据或读取 cookie 之类的操作,这将非常方便。
¥In the previous section on loading we loaded data from the server using +page.server.js
and +layout.server.js
files. This is very convenient if you need to do things like getting data directly from a database, or reading cookies.
有时在进行客户端导航时从服务器加载数据是没有意义的。例如:
¥Sometimes it doesn’t make sense to load data from the server when doing a client-side navigation. For example:
你正在从外部 API 加载数据
¥You’re loading data from an external API
你想要使用内存数据(如果可用)
¥You want to use in-memory data if it’s available
你想要延迟导航,直到图片预加载完毕,以避免弹出
¥You want to delay navigation until an image has been preloaded, to avoid pop-in
你需要从
load
返回一些无法序列化的内容(SvelteKit 使用 devalue 将服务器数据转换为 JSON),例如组件或存储¥You need to return something from
load
that can’t be serialized (SvelteKit uses devalue to turn server data into JSON), such as a component or a store
在这个练习中,我们处理后一种情况。src/routes/red/+page.server.js
、src/routes/green/+page.server.js
和 src/routes/blue/+page.server.js
中的服务器 load
函数返回一个 component
构造函数,它不能像数据一样序列化。如果你导航到 /red
、/green
或 /blue
,你将看到“从 load
返回的数据...终端中出现“不可序列化”错误。
¥In this exercise, we’re dealing with the latter case. The server load
functions in src/routes/red/+page.server.js
, src/routes/green/+page.server.js
and src/routes/blue/+page.server.js
return a component
constructor, which can’t be serialized like data. If you navigate to /red
, /green
or /blue
, you’ll see a ‘Data returned from load
... is not serializable’ error in the terminal.
要将服务器 load
函数转换为通用 load
函数,请将每个 +page.server.js
文件重命名为 +page.js
。现在,这些函数将在服务器端渲染期间在服务器上运行,但也将在应用更新或用户执行客户端导航时在浏览器中运行。
¥To turn the server load
functions into universal load
functions, rename each +page.server.js
file to +page.js
. Now, the functions will run on the server during server-side rendering, but will also run in the browser when the app hydrates or the user performs a client-side navigation.
我们现在可以像使用任何其他值一样使用从这些 load
函数返回的 component
,包括在 src/routes/+layout.svelte
中:
¥We can now use the component
returned from these load
functions like any other value, including in src/routes/+layout.svelte
:
<nav
class={[page.data.color && 'has-color']}
style:background={page.data.color ?? 'var(--bg-2)'}
>
<a href="/">home</a>
<a href="/red">red</a>
<a href="/green">green</a>
<a href="/blue">blue</a>
{#if page.data.component}
<page.data.component />
{/if}
</nav>
阅读 documentation 以了解有关服务器 load
函数和通用 load
函数之间的区别以及何时使用哪个函数的更多信息。
¥Read the documentation to learn more about the distinction between server load
functions and universal load
functions, and when to use which.
<h1>pick a colour</h1>