Vue <script setup> - how to deal with multiple dynamic components?

Viewed 1377

It seems that it is impossible to convert the Options API code below to <script setup>:

    <template>
      <div>
        <component :is="layout">
          <router-view/>
        </component>
      </div>
    </template>
    
    <script>
    const defaultLayout = 'default'
    
    import Dark from './layouts/dark.vue'
    import Light from './layouts/light.vue'
    import Default from './layouts/default.vue'
    
    export default {
      name: 'App',
    
      components: {
        Dark,
        Light,
        Default
      },
    
      computed: {
        layout () {
          return (this.$route.meta.layout || defaultLayout)
        }
      }
    }
    </script>

My attempt:

    <script setup>
    import { computed } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    
    import Dark from './layouts/dark.vue'
    import Light from './layouts/light.vue'
    import Default from './layouts/default.vue'
    
    const router = useRouter()
    const route = useRoute()
    
    const defaultLayout = 'default'
    const layout = computed(() => route.meta.layout || defaultLayout )
    </script>

Result:

No layout is loaded with the <script setup> option but just a <default>, <dark>, or <light> block, for example:

    <div id="app">
    <default>
    ...
    ...
    </default>
    </div>

According to the doc here, we can use a ternary:

    <component :is="someCondition ? Foo : Bar" />

But that is not ideal. As you might have more than 2 dynamic components to work out. We can't make the ternary too long. Can we?

Any ideas?

1 Answers

The trick is to return the referenced variable rather than it's name.

    <script setup>
    import { computed } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    
    import Dark from './layouts/dark.vue'
    import Light from './layouts/light.vue'
    import Default from './layouts/default.vue'
    
    const router = useRouter()
    const route = useRoute()
    
    const layouts = {
      default: Default,
      light: Light,
      dark: Dark
    };
    
    const defaultLayout = 'default'
    const layout = computed(() => layouts[route.meta.layout || defaultLayout] )
    </script>

Reason

While with options API components are registered locally and can be resolved by it's name (string key), with <script setup> the components are used directly without registration so it is not possible to use string key to resolve them...

Related