有时,你可能需要一起使用服务器加载函数和通用加载函数。例如,你可能需要从服务器返回数据,但还需要返回无法序列化为服务器数据的值。
¥Occasionally, you might need to use a server load function and a universal load function together. For example, you might need to return data from the server, but also return a value that can’t be serialized as server data.
在这个例子中,我们希望根据从 src/routes/+page.server.js
获得的数据是否为 cool
,从 load
返回不同的组件。
¥In this example we want to return a different component from load
depending on whether the data we got from src/routes/+page.server.js
is cool
or not.
我们可以通过 data
属性访问 src/routes/+page.js
中的服务器数据:
¥We can access server data in src/routes/+page.js
via the data
property:
export async function load({ data }) {
const module = data.cool
? await import('./CoolComponent.svelte')
: await import('./BoringComponent.svelte');
return {
component: module.default,
message: data.message
};
}
请注意,数据未合并 - 我们必须从通用
load
函数明确返回message
。¥[!NOTE] Note that the data isn’t merged — we must explicitly return
message
from the universalload
function.
<script>
let { data } = $props();
</script>
<data.component message={data.message} />