将值从布局传递到svelte sapper中的嵌套子路由



[Edit]我已经更新了示例,使其包括使用预加载(userb(和{#wait}(usera(。场景usera和userb在/users/[username]/about.svelte中均未定义

你怎么能让这样的东西发挥作用:

/users/[用户名]/_layout.svelte

{#await promise}
Loading...
<slot {usera} {userb}/>
{:then usera}
{ JSON.stringify({usera, userb}) }
<slot {usera} {userb}/>
{/await}
<script context="module">
export async function preload(page, session) {
let userb = await fetchUser(page.params.username)
return { userb };
}
</script>
<script>
import { stores } from '@sapper/app'
const { page } = stores();
export let userb;
let usera
async function fetchUser (username) {
return new Promise(resolve => setTimeout(() => {
resolve({ username });
}, 333))
}
let promise = fetchUser($page.params.username)
</script>

/users/[用户名]/about.svelte

{#if usera}
<span>{usera.username}</span>
{:else}
NULL USER_A
{/if}
{#if userb}
<span>{userb.username}</span>
{:else}
NULL USER_B
{/if}
<script>
export let usera
export let userb
$: console.log({ usera })
$: console.log({ userb })
</script>

/user/:username/about似乎没有从_layout接收到道具用户。这在nuxt中有效(基本上是vuejs的sapper,而不是svelte(。

我看不到您的proload函数。查看有关预加载的文档https://sapper.svelte.dev/docs#Preloading

您的代码中应该包含这样的内容。为了在页面呈现之前加载数据,预加载是必要的。只有当您将其包含在带有模块上下文(<script context="module">(的脚本中时,它才有效

{#await userPromise}
<p>...waiting</p>
{:then user}
<slot {user}></slot>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
<script context="module">
export async function preload({ params }) {
console.log('layout')
const { username } = params;
return { username };
}
</script>
<script>
function delay(t, v) {
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, v), t);
});
}
export let username;
export let userPromise = fetchUser($page.params.username)
</script>

相关内容

  • 没有找到相关文章

最新更新