如何在 HTML 父子关系中使用 2 个 Svelte 组件将数据从子级传递到父级 [英] How to pass data from child to parent with 2 Svelte components in HTML parent-child relationship

查看:142
本文介绍了如何在 HTML 父子关系中使用 2 个 Svelte 组件将数据从子级传递到父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Svelte 的新手.我在 HTML 父子关系中有 2 个 Svelte 组件 - 而不是 Svelte P/C 关系(其中 1 个 Svelte 组件导入另一个).

最终,我想要这样的东西(可能有很多 Accs.):

 <SvelteComponent/></手风琴>

我希望 SvelteComponent 定义 Accordion 中使用的标头(它可以是动态的).我可以为此使用商店,但这似乎太混乱了.Accordion 确实包含一个插槽,但我看不到如何向上传递信息.任何人都可以建议前进的道路吗?

解决方案

一种选择是使用组件绑定.这允许在容器组件范围内的值和所包含组件的 prop 之间进行双向绑定.

<SvelteComponent bind:header={header}/></手风琴>

在 SvelteComponent.svelte 中:

每当 SvelteComponent 对 defaultHeader 进行更改时,它都会通过与包含 Accordion 和 SvelteComponent 的文件的绑定进行备份,然后向下应用更改.https://svelte.dev/tutorial/component-bindings

或者,您可以提供一个 setHeader 函数作为 SvelteComponent 的 prop,它设置 header 的值:

//SvelteComponent.svelte<脚本>导出让 setHeader;

setHeader("myHeader")}>我的苗条组件

I'm new to Svelte. I have 2 Svelte components in an HTML parent-child relationship – as opposed to a Svelte P/C relationship (where 1 Svelte component imports another).

Ultimately, I want something like this (could have many Accs.):

  <Accordion header={--property from SvelteComponent-- }>
    <SvelteComponent />
  </Accordion>

I would like the SvelteComponent to define the header used in the Accordion (it can be dynamic). I can use stores for this but that seems too messy. Accordion does contain a slot but I can’t see how to pass information upward. Can anyone suggest a path forward?

解决方案

One option is to use component bindings. This allows a two-way binding between a value in the scope of a container component and a prop of the contained component.

<Accordion {header}>
    <SvelteComponent bind:header={header} />
</Accordion>

and in SvelteComponent.svelte:

<script>
    export let header = "defaultHeader";
</script>

Whenever SvelteComponent makes a change to defaultHeader, it will propogate back up via the binding to the file which contains the Accordion and SvelteComponent, and apply the changes back downward. https://svelte.dev/tutorial/component-bindings

Alternatively, you can provide a setHeader function as a prop to SvelteComponent, which sets the value of header:

//SvelteComponent.svelte
<script>
    export let setHeader;
</script>

<div on:click={() => setHeader("myHeader")}>
    My Svelte Component
</div>

这篇关于如何在 HTML 父子关系中使用 2 个 Svelte 组件将数据从子级传递到父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆