如何从`layout.svelte`中访问`page.svelte`中的数据。

huangapple go评论63阅读模式
英文:

how to access data from page.svelte in layout.svelte

问题

/some-route/page.svelte

export let name = 'John';

/layout.svelte

{name}  //error name is not defined
    
<script>
  ???
</script>

cant find any working example. in documentation only found with $page.data.

英文:

/some-route/page.svelte

export let name=&#39;John&#39;

/layout.svelte

{name}  //error name is not defined

&lt;script&gt;
  ???
&lt;/script&gt;

cant find any working example. in documentation only found with $page.data.

答案1

得分: 5

以下是代码的翻译部分:


与布局通过上下文进行通信的示例:

<!-- +layout.svelte -->
<script>
    import { writable } from 'svelte/store';
    import { setContext } from 'svelte';

    const errors = writable([]);
    setContext('errors', errors);
</script>

{#each $errors as error}
    <div class="error">{error}</div>
{/each}
<slot />
<!-- +page.svelte -->
<script>
    import { getContext } from 'svelte';

    const errors = getContext('errors');
</script>

<button on:click={() => $errors = [...$errors, 'oh no!']}>
    Add error
</button>
英文:

You are not supposed to. A layout can contain various pages, the data is not guaranteed to be the same. If the data is meant for the layout, move it there.


Example of communicating with layout via context:

&lt;!-- +layout.svelte --&gt;
&lt;script&gt;
	import { writable } from &#39;svelte/store&#39;;
	import { setContext } from &#39;svelte&#39;;

    const errors = writable([]);
    setContext(&#39;errors&#39;, errors);
&lt;/script&gt;

{#each $errors as error}
    &lt;div class=&quot;error&quot;&gt;{error}&lt;/div&gt;
{/each}
&lt;slot /&gt;
&lt;!-- +page.svelte --&gt;
&lt;script&gt;
	import { getContext } from &#39;svelte&#39;;

    const errors = getContext(&#39;errors&#39;);
&lt;/script&gt;

&lt;button on:click={() =&gt; $errors = [...$errors, &#39;oh no!&#39;]}&gt;
    Add error
&lt;/button&gt;

huangapple
  • 本文由 发表于 2023年3月7日 23:19:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定