【发布时间】:2022-02-01 00:41:31
【问题描述】:
所以我想不出办法从<slot> 中显示的组件中将变量向上传递到__layout 变量中。
我尝试了一些方法,在插槽上使用了bind: 或let:,但它不起作用。我得到'myvar' is not a valid binding 或<slot> cannot have directives。
我也尝试导出或不导出布局上的变量,但我真的无法让它工作......
这是我所拥有的:
<!-- __layout.svelte -->
<script>
export let myvar = undefined;
</script>
<main>
<slot myvar={myvar}></slot>
<p>Layout myvar: {myvar}</p> <!-- << This will stay undefined -->
</main>
<!-- mypage.svelte -->
<script>
import MyComponent from "$lib/my_component.svelte";
export let myvar;
let a_list_of_things = [1,2,3,4]
</script>
<main>
{#each a_list_of_things as thing}
<MyComponent bind:myvar={myvar} thing={thing}/> <!-- The variable is binded here -->
{/each}
<p>mypage myvar: {myvar}</p> <!-- << This will get the good value -->
</main>
<!-- my_component.svelte -->
<script>
import IconButton from '@smui/icon-button'
export let myvar;
export let thing;
</script>
<div>
<IconButton class="material-icons" on:click={() => myvar='something'} >
autorenew
</IconButton> <!-- << We change the value on:click here -->
</div>
所以主要目标是在布局级别上有一个与bind:myvar=myvar 等效的对象(对于<slot></slot>。
我尝试理解documentation,但没有取得多大成功,似乎更多的是关于组件槽而不是布局。
我发现this other question 建议在 sapper(sveltekit 的旧名称)中使用商店,不确定它是否与 sveltekit 的最新版本保持同步,这是要走的路吗?还是有别的办法?
Someone else 建议使用上下文。你怎么看?
我为什么需要这个?
所以我的应用程序结构如下:
__layout
├─ header (menu)
├─ my_page (<slot>)
│ └ my_component (many)
└ interactive banner
这样显示:
[ Header Menu ]
Content of the page
- component 1
- component 2
- component n
[ Current component: 2 ] << Updated when click on an elem in the component
component 定义交互式横幅应显示的内容。同样点击interactive banner可以改变components中显示的状态
【问题讨论】: