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:
<script lang=ts>
export let pos: {
x: number,
y: number,
}
</script>
Each nested component in my program is shown as following in 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.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. 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}>
. This solution does not let me bind specific values in App to specific values in 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
).
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}
?
CodePudding user response:
What you could do is export your x
and y
and build your own pos
variable from it like so:
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)
But I would suggest just using x
and y
.
CodePudding user response:
This is not supported.
You either have to not use a binding (you rarely should use those anyway), then you can inline an 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
.