user3708087 user3708087 - 1 year ago 154
Javascript Question

Using a svelte component and setting all data

I am using a nested component and I would like to set the whole

data
property for that nested component with a value from the parent component.

For instance, first
app.html
component

<NestedComponent data="{{ forNested }}" />
<script>
export default {
data: () => {
return { forNested: { a: 1, b, 2 }};
}
};
</script>


Then the nested component,
nested-component.html
, would be:

<p>Hi {{ a }} and {{ b }}</p>


Instead this means I have to do this:

<p>Hi {{ data.a }} and {{ data.b }}</p>


Is there some sort of keyword attribute to do this?




Update

Since there is no spread operator I did something like this, where you can set an arbitrarily field, like
data
and then observe that to update all properties. In the nested component:

<div class="stuff">{{ someProperty }}</div>
<script>
export default {
oncreate: function() {
// Allow data to set all propeties, since we can't set
// all from the markup of a component
this.observe('data', d => {
if (_.isPlainObject(d)) {
this.set(d);
}
});
}
}
</script>


Then when using that nested component, where
forNestedObject
is something like
{ someProperty: 123 }
:

<NestedComponent data="{{ forNestedObject }}" />

Answer Source

There isn't currently a 'spread operator' like <NestedComponent ...forNested>, though it's not inconceivable that we'd add something like that in future. For now, the most concise way to pass data down is to use the :foo directive, which means foo={{foo}}:

<NestedComponent :a :b/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download