Svelte: Dynamic component creation?

Created on 30 Nov 2016  路  2Comments  路  Source: sveltejs/svelte

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?

enhancement

Most helpful comment

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!

All 2 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Rich-Harris picture Rich-Harris  路  3Comments

juniorsd picture juniorsd  路  3Comments

st-schneider picture st-schneider  路  3Comments

noypiscripter picture noypiscripter  路  3Comments

angelozehr picture angelozehr  路  3Comments