Vue3 Fundamentals ยท Composition & Reuse

Dynamic components

Dynamic components

A screen often shows one of several components in the same spot: a tab panel, a step in a wizard, a preview that switches as you choose. Writing a v-if chain for every option gets long, and the branch you want is already a value.

Render a component from a value with the built-in <component> element and its is binding:

<script setup>
defineProps({ view: { type: Object, required: true } });
</script>

<template>
  <component :is="view" />
</template>

:is takes a component and renders it in place. Change the value and Vue swaps which component is shown, reusing the same spot in the tree. The value can also be a tag name like 'h1', but a component is the usual case.

The Test mounts your component and passes a component in the view prop. It checks that the passed component rendered its heading. The starter renders a literal <view> element instead, so no heading appears and the Test fails. Render the prop through <component :is> in App.vue.

Challenge

A screen wants to render whichever component it is handed, without a v-if chain. Export an App component from App.vue that declares a required view prop and renders it with <component :is="view" />.

The Test passes a component in the view prop and checks that its heading rendered. The starter renders a literal <view> element, so no heading appears and the Test fails. Render the prop through <component :is>.

App.vue
<script setup>
defineProps({ view: { type: Object, required: true } });
</script>

<template>
  <view />
</template>

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.