英文:
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='John'
/layout.svelte
{name} //error name is not defined
<script>
???
</script>
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:
<!-- +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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论