将值从布局传递到Svelte Sapper中的嵌套子路线?

时间:2019-11-08 15:57:26

标签: svelte sapper svelte-3

[编辑]我已经更新了示例,使其包括使用预加载(userb)和{#await}(usera)。在/users/[username]/about.svelte

中未定义usera和userb两种情况

您将如何获得类似的效果:

/ 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接收prop用户。这适用于nuxt(基本上是vuejs的替代工具,而不是svelte)。

1 个答案:

答案 0 :(得分:0)

我看不到您的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>