Hello,
Is there a way (or plans) to create components dynamically? Akin to Vue's <component :is>, perhaps.
Something that allows us to, for instance, initialize a different component for each item in a list:
{{#for children as component}}
<!-- use or initialize component -->
{{/for}}
where children could be a list of component types for construction, or maybe even component instance references for direct usage?
There aren't any concrete plans yet, no. For the time being this'd be a case of using a series of if blocks inside the loop...
{{#each children as component}}
{{#if component.type === 'foo'}}
<Foo/>
{{elseif component.type === 'bar'}}
<Bar/>
{{elseif component.type === 'baz'}}
<Baz/>
{{/if}}
{{/each}}
Or you could maybe do something like this:
<!-- ComponentSwitcher.html -->
<div ref:container></div>
<script>
import Foo from './Foo.html';
import Bar from './Bar.html';
import Baz from './Baz.html';
const components = { Foo, Bar, Baz };
export default {
onrender () {
let component;
this.observe( 'type', type => {
if ( component ) component.teardown();
const Component = new components[type];
component = new Component({
target: this.refs.container
});
});
}
};
</script>
<!-- App.html -->
{{#each children as component}}
<ComponentSwitcher type='{{component.type}}'/>
{{/each}}
<script>
import ComponentSwitcher from './ComponentSwitcher.html';
export default {
components: { ComponentSwitcher }
};
</script>
Some finessing to do around passing data around etc, but you get the idea!
Oooh, the ComponentSwitcher format seems very flexible.
I can't go with the if blocks because I don't want to create compile-time dependencies between these components (code-splitting and all that), but I can certainly work with the js API like your second example.
Thank you!
Most helpful comment
Oooh, the
ComponentSwitcherformat seems very flexible.I can't go with the
ifblocks because I don't want to create compile-time dependencies between these components (code-splitting and all that), but I can certainly work with the js API like your second example.Thank you!