简体   繁体   English

在组件之间传递对象

[英]Pass objects between components

I've intend to do the following with my objects.我打算对我的对象执行以下操作。 Hopefully, eventhough the code does not work, you'll understand the intention.希望即使代码不起作用,您也会理解其意图。

I have this component with the following coordinates in Nested.svelte:我在 Nested.svelte 中有具有以下坐标的组件:

<script lang=ts>
    export let pos: {
        x: number,
        y: number,
    }
</script>

Each nested component in my program is shown as following in App.svelte:我的程序中的每个嵌套组件在 App.svelte 中如下所示:

{#each objects as object}
    <Nested bind:pos.x={object.geometry.x} bind:pos.y={object.geometry.y}
{/each}

The objects variable is a store value with the following structure: objects变量是具有以下结构的存储值:

objects.geometry = [
    {
        x,
        y,
    }, {
        x,
        y,
    } ...
]

The problem is in sending the objects.geometry.x and objects.geomtry.y to the Nested component from the App.问题在于将objects.geometry.xobjects.geomtry.y从 App 发送到 Nested 组件。 The following code i have given does not work, and the only solution i found to work is sending the object as a whole: <Nested bind:pos={objects.geometry}> .我给出的以下代码不起作用,我发现唯一可行的解决方案是将 object 作为一个整体发送: <Nested bind:pos={objects.geometry}> This solution does not let me bind specific values in App to specific values in Nested.此解决方案不允许我将 App 中的特定值绑定到 Nested 中的特定值。 This also forces me to name the variables in the objects variable the same names as the coordinate values in Nested.svelte ( x and y ).这也迫使我将objects变量中的变量命名为与 Nested.svelte ( xy ) 中的坐标值相同的名称。

Is there another way to send object-structured data into components?是否有另一种方法可以将对象结构化数据发送到组件中? Something that would work like <Nested bind:pos.x={object.geometry.x} bind:pos.y={object.geometry.y} ?<Nested bind:pos.x={object.geometry.x} bind:pos.y={object.geometry.y}这样的东西?

This is not supported.这是不支持的。

You either have to not use a binding (you rarely should use those anyway), then you can inline an object:你要么不必使用绑定(无论如何你很少应该使用它们),然后你可以内联一个 object:

{#each objects as object}
    <Nested pos={{ x: object.geometry.x, y: object.geometry.y }} />
{/each}

Or you have to split pos into top level props x / y .或者您必须将pos拆分为顶级道具x / y

What you could do is export your x and y and build your own pos variable from it like so:您可以做的是导出您的xy并从中构建您自己的pos变量,如下所示:

export let x;
export let y;

$: pos = new Proxy({x, y}, {
    set: (_obj, key, value) => {
        if (key === "x") x = value;
        else if (key === "y") y = value;
        else return false;
        return true
    }
})

repl 重复
(If you didnt need to write to pos , you could also use $: pos = { x, y }; which will stay up to date, but since you used bind I assume you want a two way binding) (如果您不需要写入pos ,您也可以使用$: pos = { x, y };它将保持最新,但是由于您使用了 bind 我假设您想要双向绑定)

But I would suggest just using x and y .但我建议只使用xy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM